Paul
Paul

Reputation: 11746

Why is my JSON object undefined?

I'm trying to parse a JSON data structure but what I think should be data is returning undefined.

Here is the jQuery I'm using:

....
var messages = data.messages;

$.each(messages, function(i, val) {

    var user = messages[i];

    //console.log(user);
    console.log(user['msg']);

});

The PHP data structure look like this:

...
$message_info = array();

$message_info[$row['username']]['prvt'] = 1;
$message_info[$row['username']]['msg'] = stripslashes($row['message']);
$message_info[$row['username']]['ts'] = $row['timestamp'];

...

$message_list[] = $message_info;

...

$res->messages = $message_list;
echo json_encode($res);

If I dump user to the console the output look like this:Object

{john: Object}
  john: Object
  msg: "test msg"
  prvt: 0
  ts: "2012-12-10 09:16:13"

This is what data looks like in the console:

Object {success: true, lastid: "60", messages: Array[15]}
lastid: "60"
messages: Array[15]
  0: Object
    john: Object
      msg: "test msg"
      prvt: 0
      ts: "2012-12-10 09:16:13"
  1: Object
    john2: Object
      msg: "test msg2"
      prvt: 1
      ts: "2012-12-10 09:18:13"
 ...

Any idea why I can't access and retrieve the contents of msg?

Upvotes: 0

Views: 343

Answers (2)

Blazemonger
Blazemonger

Reputation: 92903

Rewrite your PHP to avoid nesting msg inside of $row['username']:

$message_info = array();
$message_info['username'] = $row['username']; // find this in JS with user['username']
$message_info['prvt'] = 1;
$message_info['msg'] = stripslashes($row['message']);
$message_info['ts'] = $row['timestamp'];

With that change, your JavaScript should work as-is.

Upvotes: 1

Julien May
Julien May

Reputation: 2051

your user objects contains an object that is referenced by the key "john", "john2" etc.

user.john.msg or user.john2.msg

should work.

Therefore to build a more generic json structure in php, i would do the following:

...
$message_info['user']['name'] = $row['username'];
$message_info['user']['prvt'] = 1;
...

Upvotes: 0

Related Questions