开发者

Ajax method within an added method in jQuery validator

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 functi开发者_如何学Goon 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: 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;
                }
        }
});


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();
          }
        }
      }
    }
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜