views:

47

answers:

2

Here is my Javascript:

$.post('foo.php', { request: Request }, function(data)
{
    $.each(data.chats, function(i, chat)
    { ... });
});

And here is the JSON that, verified by Firebug and everything else, this code is receiving:

{
    "chats": [
        {
            "chat_id": "22",
            "user_status": "Listening",
            "user_ping": "2010-06-22 15:53:57",
            "messages": [
                {
                    "chat_id": "22",
                    "line_id": "5",
                    "message": "Hello",
                    "timestamp": "15:53"
                }
            ]
        }
    ]
}

... so why, when I run this, does it not work, and Firebug throws the error that the "object is undefined", with a link to "length = object.length" on line 552 of jquery.js, and shows 'undefined' when I do a console.log(data.chats)? A console.log(data) shows the full JSON response, but for some reason it doesn't want to deal with data.chats... I've narrowed the error down the '$.each' line.

I'm reasonably sure this is a very simple mistake and I'll facepalm when someone points it out to me, but at this point I'm completely confused. (and yes, "chats" is supposed to be a JSON array, to handle multiple chats in the future, same with messages.)

+2  A: 

Is chats a JSON array in the sense that it's a string containing a JSON array, or in the sense that it's a JavaScript object? If it's the former, you'll need to convert it into the latter before you can start using it like that.

Zarel
I'm not sure I understand. The JSON I posted is the exact and total content being delivered from the server to the client (with added spacing for legibility) and being sent to the function as the 'data' parameter. The JSON itself was generated from a PHP array with json_encode().
Andrew
@Andrew - but it's not interpreted as JSON because you haven't told it that you expect JSON. It's treating it as HTML (i.e., a string) and not intepreting it because you didn't supply a response type.
tvanfosson
tvanfosson's reply has example code that shows how to get jQuery's `post` function to automatically convert the string into a JavaScript array. My reply is just explaining why you need to.
Zarel
+5  A: 

Tell it that you are expecting JSON -- by default it will treat the response as html.

$.post('foo.php', { request: Request }, function(data) 
{ 
    $.each(data.chats, function(i, chat) 
    { ... }); 
}, 'json');
tvanfosson
Enter the facepalm.
Andrew