0

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

function verifica() {
  var meuid = $('.meuid').attr('id');
  var datas = "user=" + meuid;
  $.ajax({
    type: "GET",
    url: 'sys/stream2.php',
    data: datas
  }).done(function(data) {
    //alert(data);
    $('#nome').html(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.

showdev
  • 28,454
  • 37
  • 55
  • 73
Brunno Sena
  • 11
  • 1
  • 4

1 Answers1

0

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);
Phiter
  • 14,570
  • 14
  • 50
  • 84
  • Ok , no data Have To Put my answer data[x ] . As I walk THAT data agora ... To Set the User class and to assign ? – Brunno Sena Feb 09 '16 at 01:52
  • I'm doing well , alert ( data [0 ] ) ; and it returns me : { " Usuarioon " , " 1", " status " : " fa -circle - text- red" } Okay, here. How could I do this: $ ( '#' + Data [0 ] .usuarioon . ) .addClass ( Data.[0]status ) ; @PhiterFernandes ??? – Brunno Sena Feb 09 '16 at 02:17