I just got a jQuery AJAX call to function and now I am having trouble parsing the value that I am returning. I am working with a mysql database and returning an php array()
like so to my jQuery AJAX function: echo json_encode($reservationArray);
Now, when I append this to my page in a simple div tag this is the result:
[{"reservation_id":"3","available":"0","lock":"0","restaurant":"2","date_made":"2013-12-09 18:39:52","date_of":"2014-01-02 00:00:00","time":"08:30:00","guests":"5","user":"0"},{"reservation_id":"4","available":"0","lock":"0","restaurant":"2","date_made":"2013-12-09 18:40:15","date_of":"2014-01-02 00:00:00","time":"08:00:00","guests":"7","user":"0"}]
I believe this is a proper JSON (Please, correct me if I am wrong). I have tried just about every method of accessing the data and cannot. Below is the approach that I am taking, to construct a new block of code, a bunch of rows - one per reservation (I have shortened the string for this example).
EDITED:
function my_ajax(rest_id){
$.ajax({
url: 'change_restaurant.php',
type: 'POST',
data: {'action': 'get-reservations', 'rest_id': rest_id},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div>Restaurant Name :'+item.reservation_id+' Reservation Date: '+item.restaurant+'</div>'
}
else {
return false;
}
})
$('#reservation-table').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "
" + err);
}
});
}
I believe this is a proper JSON (Please, correct me if I am wrong).
It seems that the JSON your receiving is not the correct document. As Pointy said in the comments, nowhere are there fields "name" or "date".
[{
"reservation_id" : "3",
"available" : "0",
"lock" : "0",
"restaurant" : "2",
"date_made" : "2013-12-09 18:39:52",
"date_of" : "2014-01-02 00:00:00",
"time" : "08:30:00",
"guests" : "5",
"user" : "0"
}, {
"reservation_id" : "4",
"available" : "0",
"lock" : "0",
"restaurant" : "2",
"date_made" : "2013-12-09 18:40:15",
"date_of" : "2014-01-02 00:00:00",
"time" : "08:00:00",
"guests" : "7",
"user" : "0"
}
]
You need to modify your PHP code to perform a query that joins data from reservations
and restaurants
.
You also have not instructed jQuery to expect JSON in return. It may be parsing as string. Note the dataType
option.
function my_ajax(rest_id){
$.ajax({
url: 'change_restaurant.php',
type: 'POST',
data: {'action': 'get-reservations', 'rest_id': rest_id},
dataType: "json", // EXPECT JSON
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div>Restaurant Name :'+item.reservation_id+' Reservation Date: '+item.restaurant+'</div>'
}
else {
return false;
}
})
$('#reservation-table').append(newhtml);
,
error: function(xhr, desc, err) {
console.log(xhr + "
" + err);
}
});
}