Home Ask Login Register

Developers Planet

Your answer is one click away!

Brunno Sena February 2016

Return two JSON objects to AJAX

I make an AJAX request to a PHP file as follows:

function verifica() {
  var meuid = $('.meuid').attr('id');
  var datas = "user=" + meuid;
    type: "GET",
    url: 'sys/stream2.php',
    data: datas
  }).done(function(data) {

In my PHP file, I output JSON data from a loop:

foreach ($gUsuarios as $usuarios) {
  $agora = $usuarios['AGORA'];   
  if ($agora >= $usuarios['cUsu_Limite']) {            
    echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-red'));            
  } else {    
    echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-green'));

The output is two JSON objects:

{"usuarioon":"1","status":"fa fa-circle-o text-red"}
{"usuarioon":"3","status":"fa fa-circle-o text-red"}      

How can I parse the two JSON objects in my AJAX success handler? I've tried with parseJSON, but it did not work. I think it's because I'm returning an array within a foreach.


Phiter Fernandes February 2016

You shouldn't echo multiple json strings into your Ajax request, that will make it fail.

If you do this, you will get the desired results:

$retorno = array();
foreach ($gUsuarios as $usuarios) {
  $agora = $usuarios['AGORA'];   
  if ($agora >= $usuarios['cUsu_Limite']) {            
    $retorno[] = json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-red'));            
  } else {    
    $retorno[] = json_encode(array('usuarioon' => $usuarios['cUsu_ID'], 'status' => 'fa fa-circle-o text-green'));
echo json_encode($retorno);

Post Status

Asked in February 2016
Viewed 2,560 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life