Reputation: 12512
I am using jQuery .ajax() to submit some values to db.php page where I retrieve additional records from my db. I use a class that returns the query results in a form of an object. I need to return that object back to original page in response and output it.
$.ajax({
type: 'POST',
url: '/db.php',
data: {
'item': myItem
},
dataType : 'json',
async: true,
success: function (response) {
// need returned values here
}
});
db.php
$results = $db->get_results("
SELECT *
FROM t1
WHERE id = " . $id );
// if I were to output my results here I'd do
// foreach ($results AS $res) {
// $item = $res->item;
// }
echo '{ "res": '.$results.' }';
Now sure if I need to encode anything before passing it back to my JS...
Upvotes: 0
Views: 57
Reputation: 10058
how about json_encode()
echo json_encode($result);
js:
success: function (response) {
console.log(response)
for(var i=0; i <response.length; i++){...}
}
edit: make sure you add application/json; charset=utf-8
header, if not you'll need to parse the response JSON.parse(response)
Upvotes: 1
Reputation: 49
you can do something like this with the result:
echo json_encode(array(
'result' => $result,
));
and in your success: function(response)
success: function(response){
response = JSON.parse(response);
console.log(response);
}
Upvotes: 0