0

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

1
  • 3
    PHP's json_encode is your friend. Commented Sep 25, 2015 at 20:56

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

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.