0

Process.php

<?php
    $myArray= array("John", "Rita");
    echo json_encode($myArray);
?>

myJquery.js

$.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?

3 Answers 3

1

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" );});
Sign up to request clarification or add additional context in comments.

Comments

0

You should use jQuery.parseJSON()

Example:

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

Comments

0

Use JSON Parse like this

$.post('Process.php', $(this).serialize(), function(data){
var data= JSON.parse(data);
alert(data[0]);
}

Comments

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.