views:

2722

answers:

7

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!

A: 

Your data is a string of '[{}]' at that point in time, you can eval it like so:

function(data) {
    data = eval( '(' + data + ')' )
}

However this method is far from secure, this will be a bit more work but the best practice is to parse it with Crockford's JSON parser: http://json.org/json2.js

Another method would be $.getJSON and you'll need to set the dataType to json for a pure jQuery reliant method.

meder
Does this not only work if the array that php jason_encodes is a single level array? For example, see the original code that generates the JSON object. Only in the event that the database query generates no results is the array one-dimensional, otherwise it is multidimensional.
oh I didn't see that part.. hm
meder
Ok - you should still be evaluating it, it's now a string at that point in your code I believe.
meder
A: 

You can use the Javascript eval() function to parse the JSON for you. See the JSON website for a better explanation, but you should be able to change your success function to...

var returnedObjects = eval(data);
var i = 0;
for (i = 0; i < returnedObjects.length; i++){
    console.log('Time: ' + returnedObjects[i].time);
}

...or something close.

BenN
I think that is effectively what $.each is supposed to do, and I thought using $.ajax with a json datatype meant that the response data came pre-eval-ed. I will try it though :)
A: 

Careful with the eval, the JSON specs http://json.org/js.html recommend something like

var myObject = eval('(' + myJSONtext + ')');

And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:

http://code.google.com/p/jquery-json/

Victor
wow, this plugin looks nice!
cimnine
+4  A: 

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 http://json.org/json2.js

Cesar
From the JSON page: `The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues`
meder
Thank you. I correct my text.
Cesar
A: 

You can download a JSON parser from a link on the JSON.org website which works great, you can also stringify you JSON to view the contents.

Also, if you're using EVAL and it's a JSON array then you'll need to use the following synrax:

eval('([' + jsonData + '])');

Fermin
A: 

Do NOT eval. use a real parser, i.e., from json.org

jamie
A: 

jQuery.parseJSON - new in jQuery 1.4.1

valums