Reputation: 593
Using the following jQuery, how can I read through the values of the JSON that's returned? With it how it is, the jQuery doesn't even run as there is an error in: alert("A" + obj.sender[0]);
var session_id = $(this).find(".session_id").val();
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: {sesh_id: session_id},
success: function (response) {
var obj = jQuery.parseJSON(response);
alert("A" + obj.sender[0]);
},
error: function (response) {
alert("Err: " + response.status);
}
});
The value of response is:
[{
"sender":"[email protected]",
"details":"details1",
"date":"2017-01-04 16:11:04"
},
{
"sender":"[email protected]",
"details":"details2",
"date":"2017-01-04 16:11:05"
},
{
"sender":"[email protected]",
"details":"details3",
"date":"2017-01-04 16:11:06"
}]
Upvotes: 1
Views: 41
Reputation: 337560
The issue you have is that your index accessor is in the wrong place as obj
is an array, not the sender
property, so it should be obj[0].sender
.
You also don't need to call JSON.parse()
on the response, as jQuery does that for you automatically as you specified dataType: 'json'
. Try this:
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: { sesh_id: session_id },
success: function (response) {
console.log("A" + obj[0].sender);
},
error: function (response) {
console.log("Err: " + response.status);
}
});
Finally, note that console.log()
is much more preferable when debugging over alert()
as it doesn't coerce data types.
Upvotes: 1