Reputation: 740
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)
Upvotes: 0
Views: 975
Reputation: 5115
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.partone
and data.parttwo
. Also worth mentioning, you should define the dataType
in 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.
Upvotes: 4
Reputation: 38345
An AJAX call only returns one response, which is stored in that data
variable. However, what your server-side code returns as that response is up to you, and what you do with it in your Javascript is also up to you.
Assuming you're returning some HTML that you want to make the contents of some elements on your page, what you could do is separate the two parts in a way you can distinguish with Javascript. Perhaps something along the lines of:
/* part one here */|parttwo|/* part two here */
Then you just need to split data
on the '|parttwo|' string, and use the elements of the resulting array to set the contents of your different elements.
Upvotes: 0