2

test.php includes this:

echo json_encode( array(
  array("name"=>"John","time"=>"2pm"),
  array("name"=>"2","time"=>"1242pm"),
  array("name"=>"J231ohn","time"=>"2p213m"),
));

jQuery:

$.get("test.php", function(data) {
  $.each(data, function(n, val) {
    alert(n + ': ' + val)
  });
}, "json");

This is the result:

0: [object Object]
1: [object Object]
2: [object Object]

What am I doing wrong?

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
Norbert
  • 2,741
  • 8
  • 56
  • 111

6 Answers6

5

Try:

alert(n + ': name = ' + val.name + ' time = ' + val.time);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

I dont know php but my guess is you need to do this instead, as each val is a json object.

$.get("test.php", function(data) {
  $.each(data, function(n, val) {
    alert(n + ': ' + val.name + ' ' + val.time)
  });
}, "json");

jsfiddle example

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
2

Use console.log(data) to get a decent look at what's inside your JSON from the console in Firebug or Webkit.

Great tutorial here: http://jqueryfordesigners.com/debugging-tools/

Mark Holland
  • 846
  • 4
  • 8
1

Use .getJSON. Try:

$.getJSON("test.php", function(data) {
     $.each(data, function(n, val) {
         alert(n + ': ' + val)
     });
});
TNS MUMET
  • 11
  • 1
1

Technically, nothing. 'val' references the object, which I suspect isn't what you want. You probably want the values stored in each array. So, instead of alerting out 'val', you probably want to access the array key values:

alert(n + ': ' + val.name + ' ' + val.time)
Brian Flanagan
  • 4,612
  • 5
  • 29
  • 38
0

depending on your browser, you could call val.toSource() which will spill the objects contents instead of its type (which is the default behaviour for .toString() )

a nice, shorthand way to write this is alert ([n, val.toSource() ]);

Ken Egozi
  • 1,825
  • 11
  • 14