簡體   English   中英

使用Jquery和AJAX進行表單驗證

[英]Form Validation with Jquery and AJAX

我正在使用AJAX和JQUERY來調用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;
        }
    }
    });
}

    });

嘗試更新這些:

$("#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

如果您絕對必須使用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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM