I have the following function which I use to check whether or not an email address is already registered.
checkTaken() {
var email_var = $('input#email').val();
$.post("../includes/check_email.inc.php",{email:email_var} ,function(data) {
var ret = data + "";
if(ret=="true") {//if username not avaiable
$('div#emailTaken').show();
$('input#email').addClass('redBack');
return false;
} else {
$('div#emailTaken').hide();
$('input#email').removeClass('redBack');
return true;
}
});
}
When I call it using something like the following it works fine:
email.blur(checkTaken);
But when I do something like
var test1 = checkTaken();
or
if(chekTaken) {
something quirky happens. It enters the function, executes the $.post line, but then never enters the rest of the routine. Why is this? And how do I fix it?
As a note, when I call the function using the last two examples, I do get information back from the server as seen through firebug.If I add a watch for test1, it remains undefined.
That is happening because
checkTaken()does not wait for the$.postto finish before returning, due to the fact that$.postwill fire off an asynchronous request to the server. What you can do is use$.ajaxinstead and set theasyncoption tofalse(bearing in mind that it will block the browser momentarily while it waits for the request completes).