I’m kind of stuck with this pretty simple (I’m sure) jQuery/Javascript issue.
Here’s the code :
jQuery.validator.addMethod("emailExists", function(value, element, param) {
var email = value || '';
var valid = 0;
$.ajax({
type: "POST",
url: param,
data: "email=" + email,
success: function(msg) {
if (msg != '' && msg)
{
valid = 0;
}
else
{
valid = 1;
}
}
});
return valid;
}, "* Email address already registered, please login.");
This function is called where a user type his email address in a registration form, and everything seems to work perfectly, except that my valid variable returned isn’t updated, whereas when I use an alert box it is properly done!
It looks like it return the value before the AJAX is done, any idea?
Cheers,
Nicolas.
Your code fails, because ajax works asynchronously. your return statement is reached before the success function is called. To make it synchronous add
async: falseto your ajax call like this: