使用Jquery和AJAX进行表单验证

时间:2014-01-16 14:27:51

标签: javascript php jquery ajax

我正在使用带有JQUERY的AJAX来调用PHP脚本来验证用户电子邮件。但是,由于某种原因,表格即使不应该提交。我究竟做错了什么?我知道错误肯定不在我的PHP中。

我的代码:

$("#signup").submit(function() {

var error= false;

var dataString = $(this).serialize();
var email= $("#email").val().trim();


if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
    $.ajax({  
    type: "POST",  
    url: "checkemail.php",  
    data: dataString,
        async: false,
    success: function(data) {
        var error= false;

        if (data == 'invalid') {
        var invalid= 1;
        }
        else if (data == 'taken') {
        var taken= 1;
        }
        if (invalid == 1) {
        alert('invalid email');
            error = true;
        }
        if (taken == 1) {
        alert('email taken');
        error = true;
        }
        if (error == true) {
        return false;
        }
    }
    });
}

    });

2 个答案:

答案 0 :(得分:2)

尝试更新这些:

$("#signup").submit(function(e) {  //<----pass the event here as "e"
    e.preventDefault();  //<----stops the form submission
    var error= false;

    var dataString = $(this).serialize();
    var email= $.trim($("#email").val());  //<----use trim this way

答案 1 :(得分:0)

如果您绝对必须使用AJAX进行表单提交,这可能是更好的方法:

$('form').submit({

      $.ajax({
           type:'post',
           url: 'someurl.php',
           data: dataString,
           context: this, // this here refers to the form object
           success:function(data)
           {
               // perform your operations here
               if(something_is_wrong)
               {
                   // show message to user
               }
               else
               {
                    this.submit(); // put this code in the block where all is ok
               }

           }
      });

    return false; // makes sure the form doesn't submit

});