[jquery] How to parse JSON array in jQuery?

EDIT I checked the jQuery documentation and using $.ajax with the json datatype specified returns an evaluated javascript object, so eval() isn't the answer here. I knew that anyway, since I am able to parse single JSON objects, just not arrays. The problem is the $.each-ing my way through them :)

I have followed the syntax for parsing a JSON array in jQuery to the letter, but it doesn't work for some reason. I am fetching the array using $.ajax, have specified the correct datatype, and in Firebug can see that the response from my PHP script is []. Yet when I try to use $.each to iterate through the array, all I get is undefined values when I try to console.log various parts of the array. Here is where my php script makes and encodes the array:

if(mysqli_num_rows($new_res) > 0) {
$messages = array();

while($message_data = mysqli_fetch_assoc($query_res)) {
  $message = array(
    'poster' => $message_data['poster'],
    'message' => $message_data['message'],
    'time' => $message_data['time']
  );

  $messages[] = $message;
}

echo json_encode($messages);
} else if(mysqli_num_rows($new_res) == 0) {
$message = array(
  'poster' => '',
  'message' => 'No messages!',
  'time' => 1
);

echo json_encode($message);
}

And here is my attempt to parse it:

   var logged_in = '<?php echo $logged_in; ?>';
   var poster = '<?php echo $_SESSION["poster"];?>';
     $.ajax({
     url: 'do_chat.php5',
     type: 'post',
     data: ({'poster':poster,'logged_in':logged_in}),
     dataType: 'json',
     success: function(data) {
         $.each(data, function(messageIndex, message) {
                    console.log(parseInt($('#chatWindow :last-child > span').html())+' '+message['time']);
       if((parseInt(message['time']) > parseInt($('#chatWindow :last-child > span').html()))) {
     $('#chatWindow').append('<div class="poster">'+message['poster']+'</div><div class="message"><span>'+message['time']+'</span>'+message['message']+'</div>');
       }
       });
     }
     });

Without the $.each function I am able to successfully parse single JSON objects, but not an array. This is my first outing with JSON and $.each, and I'm pretty new to jQuery, so go easy if my code has ugly bits!

This question is related to jquery arrays json each

The answer is


No, with eval is not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data); For this use the lib https://github.com/douglascrockford/JSON-js


Similar questions with jquery tag:

Similar questions with arrays tag:

Similar questions with json tag:

Similar questions with each tag: