Reputation: 35
My current code:
else{
$.post("ajax/ajax_login.php",
{register_username : $(selector).val()}
,function(ajax_data){
if(ajax_data == 0){
output_error(selector, "is already taken.");
return false;
}
});
output_error(selector, 0);
return true;
}
As you can see, I am doing a $.post to see if a username is already taken. IF it's taken, the ajax.php file will return a value of 0. The if(ajax_data == 0) will be true.
My problem: in that if statement i want to return false, and then NOT continue. But instead it continues out of the $.post and also hides my output.
Is there a way to break out of this $.post and NOT continue with the code below. (I even think the code below executes BEFORE the $.post code)
Upvotes: 0
Views: 30
Reputation: 17710
Ajax calls are asynchronous, so, yes, the code after the $.post()
is indeed executed before the POST has completed. Change your completion handler with something like:
if (ajax_data == 0)
output_error(selector, "is already taken");
else
output_error(selector, 0);
Note that you can't decide there what the calling function will return, as it will have finished executing already. If you need to pass back something, you'll need to set up a callback as well:
function doSomethingWhichRequiresAPost(some_parameter,callback)
{
// ... some other stuff ...
$.post("ajax/ajax_login.php",
{register_username : $(selector).val()},
function(ajax_data)
{
if (ajax_data == 0)
{
output_error(selector, "is already taken.");
callback(false);
}
else
{
output_error(selector, 0);
callback(true);
}
}
);
}
Now, instead of calling your function and checking its return value to do something:
if (doSomethingWhichRequiresAPost(parameter))
// stuff to do if true
else
// stuff to do if false
You pass a callback:
doSomethingWhichRequiresAPost(parameter,function(ret)
{
if (ret)
// stuff to do if true
else
// stuff to do if false
}
);
Upvotes: 1