0

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

Michael Samuel
  • 3,820
  • 12
  • 45
  • 85

2 Answers2

2

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
Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
  • how can i loop through all array values? this returns only the first pair...if i have multiple how can access all elements? – Michael Samuel Sep 30 '14 at 19:27
  • You can use for loop. `for (var i = 0; i < data.length; i++) { alert(data[i].user); }` – Apul Gupta Sep 30 '14 at 19:30
  • one last question. what about if `user` is different each time like the following json string: `[{"hey":25},{"mate":12}]` – Michael Samuel Sep 30 '14 at 19:45
  • You need to use another loop. `for (var i = 0; i < data.length; i++) { for(key in data[i]){ console.log(data[i][key]); } }` – Apul Gupta Sep 30 '14 at 19:53
  • how can I do the same loop in jquery? currently i have `$.each(data, function(i, item) { $.each(data[i], function(j, key) { alert(data[j][key]); }); });` – Michael Samuel Sep 30 '14 at 20:00
2

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?

Community
  • 1
  • 1
Mike Willis
  • 1,493
  • 15
  • 30