Skip to content Skip to sidebar Skip to footer

Decoding An Json Array (from Php) In Javascript (jquery)

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('noti

Solution 1:

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

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

If you want to enumerate over these values

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

Solution 2:

@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');

Post a Comment for "Decoding An Json Array (from Php) In Javascript (jquery)"