Bartosz Rychlicki
Bartosz Rychlicki

Reputation: 1918

Add diffrent data types for javascript ajax response

I've got this problem, is there any reasonable way to return in one XHR request two types of data somehow? For example I want to return an html with some data but aside to that some variables in JSON or plain text.

In this case, I'm working on ajax pagination, there is a request with returns html with next results but I also need a integer with total count of results back from the server.

I see two options:

but both of those ways seems not elegant.

Any idea perhaps how this can be achieve?

Upvotes: 0

Views: 141

Answers (1)

Vlad Preda
Vlad Preda

Reputation: 9920

Return a JSON encoded array.

$return = array(
    'html' => '<div><!-- insert a lot of html here --></div>',
    'productId' => 3,
    'someArray' => array(1, 2, 3, 'string')
);
echo json_encode($return);

And then in javascript:

obj = JSON.parse(data); // data is return from the ajax request.

Upvotes: 1

Related Questions