How can I use the PHP data returned to a jquery $.post() function?
Question
If I need data on the fly from a script, I usually do a jQuery $.post() method and then on the backend, my PHP script echo's the info I need.
This sounds like a stupid question, but is there a way to actually just get something returned and then use that data in javascript?
My example is
$.post('script.php', vars,
function(data) {
console.log(data);
});
So i can console.log the data and this is what I get
But how can I actually use that data? Is there something I'm missing? I want to be able to go
return $data;
in PHP, and then use that data in javascript. Please tell me if this is a stupid question and I'm going down the wrong path.
Solution
For one, you can turn that data into a json object, and use it in your js
your php:
exit(json_encode($data));
your jquery
$.post('script.php', vars,
function(data) {
console.log(data);
}, 'json');
If you look at your console, data is now a javascript object
OTHER TIPS
from php
echo json_encode($data);
from jquery
$.post('script.php', vars,
function(data) {
var new_data = $.parseJSON(data);
console.log(new_data);
});