Possible Duplicate:
return AJAX callback return
I have made a JQuery code using AJAX, but despite all my efforts (trying $.post, $.get and $.ajax) I am not able to get any response nor using it in my code.
Example code:
var r = $.post("ajaxpage.php", function(data) {return data});
console.log(r); // nothing
One of the most common misconceptions of beginner programmers about Javascript and AJAX is to treat the AJAX request as a “normal” function, doing variable assignments or expecting to use immediately the AJAX response in their code.
That’s not how it works though; let’s try to understand how a correct implementation works.
AJAX stands for Asynchronous JavaScript and XML.
We will ignore for a while the XML part (which is more about how the request is carried on, via
XMLHttpObject), the Javascript bit is quite obvious (it’s the scripting language we use, with or without JQuery), let’s focus on asynchronous.AJAX works in a similar way: from client-side, you make a request to a server-side page, and expect an action (like writing a row in a database) or a response (some data fetched server-side from the page you are calling.
The important bit is that your JavaScript code continues its execution regardless of the completion of the round-trip, as there can be a significant delay when your client (remember that JS runs client-side) makes an AJAX call to the server (slow server, slow connection, and so on).
So you can’t expect to do things like:
because
$.postdoesn’t actually “return” a value like a “regular” function, the variablercannot be valued by $.postInstead, you should organize your code based on the
doneevent, which is fired after the AJAX call has completed: it guarantees (if there have been no failures, like server-side errors, not found pages, etc.) that we actually have a response to use in your code on success.With that event we can call a function that receives the response as a parameter and actually uses it.
A shorthand for this would be:
Edit: i’m not a native English speaker, forgive my mistakes.