views:

18

answers:

2

Hi, 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.

A: 

There is the remote rule option that lets you do something like this:

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $("#username").val();
          }
        }
      }
    }
  }
});
PetersenDidIt
Yeah I saw that, but didn't help me with the issue :)
Nicolas
A: 

Your code fails, because ajax works asynchronously. your return statement is reached before the success function is called. To make it synchronous add async: false to your ajax call like this:

$.ajaxA({
  async: false,
  type: "POST",
  url: param,
  data: "email=" + email,
  success: function(msg) {
                if (msg != '' && msg)
                {
                    valid = 0;
                }
                else
                {
                    valid = 1;
                }
        }
});
jigfox
Wokrs perfectly thanks! I know ajax works asynchronously, that's why I could precisely say where the issue was, but I didn't know there was a property to prevent JS, thanks!
Nicolas