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?

2

6 Answers 6

5

Try:

alert(n + ': name = ' + val.name + ' time = ' + val.time);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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/

Comments

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)

Comments

1

Use .getJSON. Try:

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

Comments

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() ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.