0

I first write the JSON:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
print json_encode(array(
    "array" => $arr
));

Then in the jQuery I do:

j.post("notifications.php", {}, function(data){

Now this is where I'm a little confused, as I would normally do:

data.array

To get the data, but I'm not sure how to handle the array. data.array[1] didn't work.

Thanks!

2
  • 3
    Have you tried a console.log() with Firebug on? It should show you how the data is received on the JS end. Commented Jul 15, 2010 at 16:51
  • @Adam good point - it is an array, not an object. @Pete that's probably your solution Commented Jul 15, 2010 at 16:51

2 Answers 2

1

PHP's associative arrays become objects (hashes) in javascript.

data.array.a === 1
data.array.b === 2
// etc

If you want to enumerate over these values

for ( var p in data.array )
{
  if ( data.array.hasOwnProperty( p ) )
  {
    alert( p + ' = ' + data.array[p] );
  }
}
0

@Peter already explained, that associative arrays are encoded as JSON objects in PHP.

So you could also change your PHP array to:

$arr = array(1,2,3,4,5); // or array('a', 'b', 'c', 'd', 'e');

However, another important point is to make sure that jQuery recognizes the response from the server as JSON and not as text. For that, pass a fourth parameter to the post() function:

j.post("notifications.php", {}, function(data){...}, 'json');
0

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.