Reputation: 4834
There are about a million posts on SO about async callbacks, but I cannot figure out how to get mine to work
I have an AJAX request:
function checkName();
var ajax = new XMLHttpRequest();
ajax.open("POST", "index.php", true); // true = async
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var pass = ajax.responseText + 0;
}
}
ajax.send("emailcheck="+email);
return pass;
}
The only possible outcomes for pass
are 1 or 0.
I've tried moving the return immediately after the assignment of pass
, but still nothing. That's when I started looking around on here and found callbacks, but I'm having trouble figuring out how to do it.
What I would like to do is have something like:
if(checkName()){
// Do stuff
}else{}
I don't want to do a synchronous ajax request (i.e. false
for third param), because that stops an animation I have and also prevents the user from performing other tasks on the site for the short time the call takes place.
I know this is very similar to other posts about the topic, I just can't quite figure it out.
Thank you in advance.
Upvotes: 0
Views: 47
Reputation: 13294
Only with a synchronous call you can implement this. And no one would want that. You said it yourself.
if(checkName()){
// Do stuff
}else{}
You need to use a callback function indeed. See this example:
function checkName(callBack) {
var ajax = new XMLHttpRequest();
ajax.open("POST", "index.php", true); // true = async
if (callBack)
{
ajax.callBack = callBack;
}
ajax.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if (this.callBack)
{
this.callBack(this.responseText);
}
}
}
ajax.send("emailcheck="+email);
}
function checkNameFinish(data)
{
alert(data);
}
checkName(checkNameFinish);
checkName
now accepts an argument callBack
. This has to be a function. When the readystate completes it checks if there's a callBack
set. If so then execute the callBack function
and pass the response as argument.
Upvotes: 2