In a simple ajax post example:
$.post('ajax/test.php', function(data) {
$('.result').html(data);
});
Is there any way to separate the result data to do two different things? ie:
$.post('ajax/test.php', function(data) {
$('.result').html(data.partone);
$('.other-result').html(data.parttwo);
});
I run an ajax request when the page is loaded and I’m trying to get everything I need in one POST. If this is possible, how do you define the different data parts on the PHP side? (ie: data.partone and data.parttwo)
You can return the data as JSON encoded string, using json_encode() on an associative array, for example:
echo json_encode(array("partone" => "data1", "parttwo" => "data2"));That way you could access it as
data.partoneanddata.parttwo. Also worth mentioning, you should define thedataTypein the$.post()to be read as JSON. For that, you need to add another parameter to it, specifying the type of data you are returning – JSON.For example:
$.post('ajax/test.php', function(data) { ... }, "JSON");Also worth mentioning, that you should return ONLY this
json_encode()output back from the ajax script, else jQuery won’t be able to parse it right.