I’m unclear about return value of the following dummy code:
function foo()
var ret = 0;
var xhr=send_request( "bla", function() {
// do something with the AJAX response
// based on the value of response, var ret get set
} );
return ret;
}
What I would like to achieve is that: based on the AJAX response, I might decide to try the request again. But the function above always returns 0 regardlessly.
Apparently I can make the foo() function decide to call send_request() twice when needed but it’s a bit ugly. Is there a easy and nice way to do this?
Thanks
You are trying to make the ajax call synchronously, but you are a making an asynchronous call.
It is important to understand that the way you have it written, the code does not wait for the AJAX call to finish before moving on to the next line. Therefore, it always returns the initial value of
ret.Do several things to fix this:
asyncto false.Should look something like this:
EDIT: It is possible to do this with an asynchronous call, but you have to adjust the way you think about the problem. Rather than thinking about return values, you have to think about callback functions.
For the sake of example, lets say I’m trying to get the user’s name and put it on the page. My code would look something like this: