Sajjad Sajjad - 1 year ago 79
jQuery Question

How to access array elements from json_encode in jquery?


$myArray= array("John", "Rita");
echo json_encode($myArray);


$.post('Process.php', $(this).serialize(), function(data) {
alert(data); // output is: ["John", "Rita"]
alert(typeof(data)); // output is: string
alert(data.length);// output is: 19
alert(data[0]); // output is: [ //How can I get John here?

var person = ["John", "Rita"];
alert(typeof(person)); // output is: object
alert(person.length);// output is: 2
alert(person[0]);// output is: John
}).fail(function() {
alert( "Some Problem Occured");

For an array of jquery, I can easily access array elements, as shown above. But for an array obtained by json_encode in jquery, I am not able to access array elemts. Please, guide me what correction I need in Jquery file?

Answer Source

You can use JSON.parse(data) or $.parseJSON(data) to create a JSON object from the string.

Or you can add parameter to the $.post(); to tell it, the response will be a json object.

$.post('Process.php', $(this).serialize(), function(data){

}, 'json') // <--- here you can add json
.fail(function() {alert( "Some Problem Occured" );});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download