tags:

views:

101

answers:

3

I am playing around with parsing JSON in jQuery and I am having trouble. I want to check the value of 'time' in the JSON object. Here is my trial function:

$.ajax({
     url: 'do_chat.php5',
     type: 'post',
     data: ({'message':'','poster':poster,'logged_in':logged_in}),
     dataType: 'json',
     success: function(data) {
       $.each(data, function(interval, message) {
       if(message['time']) {
     $('#chatWindow').append('<p>hi</p>');
       }
 });
     }
     });

The string being returned from my server looks like:

{"poster":"","message":"No messages!","time":1256084677}

I am not sure of the syntax of $.each. I am using PHP to encode the JSON string, which started life as a php assoc array. I'm sure my mistakes are plenty and any help is greatly appreciated!

Edit: follow up question - how do I make PHP generate a JSON array? At the moment I use this to generate the single object:

$messages = mysqli_fetch_assoc($new_res);
 $msg = $messages["content"];
 $who = $messages["poster"];
 $time = $messages["time_added"];
$message = array(
  'poster' => $who,
  'message' => $msg,
  'time' => $time
);

echo json_encode($message);

But if I were to get more than one row from my database query, how do I do that?

A: 
$.ajax({
     url: 'do_chat.php5',
     type: 'post',
     data: ({'message':'','poster':poster,'logged_in':logged_in}),
     dataType: 'json',
     success: function(data) {
         if (typeof data.time != 'undefined') {
             $('#chatWindow').append('<p>' + data.poster + ' - ' + data.message + '</p>');
         }
     });
});
cballou
A: 

I end up using a JSON parser from http://json.org:

$.ajax({
    type: "POST",
    url: "getData.asmx/retrieveSubcontractorList",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{}",
    success: function(result2) {
        var toolsData = JSON.parse(result2.d);

The trick was that the data is actually in a property called d.

James Black
+2  A: 

The problem with your code is that you are returning a single JSON Object {"poster":"","message":"No messages!","time":1256084677}, but you are then iterating through it with $.each.

$.each expects an array, and since you are not returning an array, the $.each is looping through the elements of your JSON object instead.

To fix your code, you need to either make sure your server is returning an array, like: [{"poster":"","message":"No messages!","time":1256084677}]

or

Remove the $.each, so that you have:

$.ajax({
    url: 'do_chat.php5',
    type: 'post',
    data: ({'message':'','poster':poster,'logged_in':logged_in}),
    dataType: 'json',
    success: function(data) {
        if(data['time']) {
            $('#chatWindow').append('<p>hi</p>');
        }
    }
});
Idris