Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple values in jQuery AJAX call

Tags:

json

jquery

I have a jQuery post function that returns a response on success after the click of a div. However, I would like to return multiple variables on success. Do I have to use JSON, and if so, is it possible to integrate it into the $.ajax function after success?

$.ajax({
   type: "POST",
   data: "action=favorite&username=" + username + "&topic_id=" + topic_id + "&token=" + token,
   url: "favorite.php",
   success: function(response) {

   }
});

EDIT
I appreciate everyone's help + 1 to all!

like image 477
Scarface Avatar asked Apr 03 '10 15:04

Scarface


2 Answers

It would be a very good idea to use only JSON responses from the server. That way your server backend would act as a JSON-RPC server and the front-end would be completely independent of it! Of course you can use JSON with the $.ajax function. Here's an example:

$.ajax({
    url: 'http://some.url.com/',
    data: 'some=post&data=xyz',
    type: 'POST',
    dataType: 'json',
    success: function(response, statusText) {
        // `response` here is a valid JSON object; jQuery handles the work of parsing the response, etc.
    }
});
like image 179
themoondothshine Avatar answered Nov 08 '22 13:11

themoondothshine


I have a jquery post function that returns a response on success after the click of a div. However, I would like to return multiple variables on success.

You can only return one value - a blob of text (in most cases).

You can, however, structure that text, so you can easily extract different bits of data from it.

Do I have to use JSON

No, but it is the simplest option.

, and if so, is it possible to integrate it into the $.ajax function after success?

Umm. Yes. Did you read the manual for the jQuery ajax function? It explicitly mentions using JSON and getting an object as the argument to the success function.

like image 38
Quentin Avatar answered Nov 08 '22 13:11

Quentin