Reputation: 1293
I am having trouble using the json object echoed from php to javascript. In the php file I define
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo($json);
and then in javascript file I want to access this object.
$("#test_btn").click(function() {
$.get("serverside.php", function(data, status) {
console.log("data " , data["a"]); //undefined
console.log(JSON.parse(data)); // error
});
});
I get undefined for data["a"] and an error for JSON.parse. How should I use the returend data?
Upvotes: 0
Views: 176
Reputation: 922
The problem might be that PHP is returning a string that looks like JSON.
In JS it might help to JSON.parse(data) to convert from string to JSON object, then you can access it.
$("#test_btn").click(function() {
$.get("serverside.php", function(data, status) {
$json = JSON.parse(data);
console.log("data " , $json["a"]); // should now return 1
});
});
Upvotes: 0
Reputation: 91734
Based on your comment (echoing several json strings), you should do the following:
json_decode()
;json_encode()
to encode and echo out your results array.Upvotes: 3
Reputation: 5427
You must make a JSON.parse(data)
before attempting to access to data['a']
, and send a header from PHP that implicitly say the browser that the data output is going to be a JSON.
header ('Content-Type: application/json');
Upvotes: 1