Reputation: 3920
I have the following PHP associative array output as a response to jquery post request:
Array
(
[0] => Array
(
[user] => 25
)
)
How can iterate through the above PHP associative array in javascript or jquery? Is this possible? or should I print the output of PHP in another way? I have access to the PHP as well
Upvotes: 0
Views: 1032
Reputation: 3034
In PHP just echo using json_encode
:
$array = array(array('user' => 25));
echo json_encode($array); // [{"user":25}]
In Jquery:
var data = $.parseJSON(jsonString); // '[{"user":25}]'
console.log(data[0].user); // 25
Upvotes: 2
Reputation: 1512
Here's what I use in a similar application:
PHP:
header("Content-Type: application/json");
if ( $_REQUEST["jsoncallback"] ) {
$callback = htmlentities( $_REQUEST["jsoncallback"] );
}
$output = json_encode( $array );
if ( $callback ) {
$output = $callback . "(" . $output . ")"; // I know the variables can be embedded in the strings, I don't care, I like it this way.
}
echo $output;
Javascript:
var getURL = "http://www.example.com/script.php?jsoncallback=?";
jQuery.ajax({
dataType: "json",
url: getURL,
success: function(data){
var obj = jQuery.parseJSON( data );
// now you can loop through the data object
}
});
For the looping part, this question/answer might be helpful: How to Loop through plain JavaScript object with objects as members?
Upvotes: 2