Return multiple values in jQuery AJAX call
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.
}
});
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.
You would have to return JSON (or some other data format supported by jQuery's ajax() function) from favorite.php.
edit: it doesn't have to be json, but for multiple return values, it is the easiest to parse. For instance, if you returned xml or html, you'd have to traverse nodes to return a value.
For instance, if you returned:
{"user": "Joe", "success" : "pass", "message" : "favorite added" }
in success, you would use:
function(response){
var user = response.user;
var success = response.success; // etc.
}
The important thing to remember is to specify the dataType in your ajax call as json. jQuery also supports the other dataTypes: xml, html, script, jsonp, text
I believe the default is html. And, having written php to return xml with properly formatted headers in the php script, I can tell you that sometimes you have to specify the dataType for jQuery to parse it correctly.