Cheyne
Cheyne

Reputation: 2137

Handling JSON Object With jQuery?

I'm having trouble handling a JSON object that I'm getting back from an AJAX request.

It's a simple flat JSON object, and all I want to do is write the responses back onto the page.

Can anyone point out how to loop over these objects and output the values? I just keep getting [undefined] or [object] written

Code here:

$.ajax({  
          type: "POST",  
          url: "func/chatResponse.php",  
          data: dataString,  
          success: function() {  
            $.getJSON('func/chatResponse.php?a=jsonLatest', function(data) {
                $.each(data, function(index) {
                    //items.push('<li id="' + key + '">' + val + '</li>');
                    $('body').append('<li id="' + data.user + '">' + data.user + '</li>');
                    alert(data);
                 });
            });
            alert("done");
          }  
        });  

JSON sample here

[
    {"user":"someguy","message":"my message","timestamp":"2011-04-19 17:26:09"},
    {"user":"Cheyne","message":"Hey There ...  Nice site","timestamp":"2011-04-19 17:26:09"}
]

Upvotes: 2

Views: 11067

Answers (2)

Ry-
Ry-

Reputation: 225281

What you want is

                 $.each(data, function(index) {
                    //items.push('<li id="' + key + '">' + val + '</li>');
                    $('body').append('<li id="' + data[index].user + '">' + data[index].user + '</li>');
                    alert(data);
                 });

Upvotes: 0

David Tang
David Tang

Reputation: 93714

data is the array, while you want the items inside the array.

$.each doesn't change data to become the items, instead it passes individual items as the second parameter to the function you supply:

$.each(data, function (index, item) {
    // Use item in here
    $('body').append('<li id="' + item.user + '">' + item.user + '</li>');
});

Alternatively, you can use data[index]:

$.each(data, function (index) {
    // use data[index] in here
    $('body').append('<li id="' + data[index].user + '">' + data[index].user + '</li>');
});

By the way, avoid ugly string concatenation with:

$('<li>', {id: item.user, text: item.user}).appendTo('body');

Upvotes: 12

Related Questions