jquery Ajax表单需要2次点击才能提交 [英] Jquery Ajax Form Requires 2 Clicks to submit

查看:94
本文介绍了jquery Ajax表单需要2次点击才能提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是HTML表单...

 < div class =box3> 
< form method =postname =loginformaction =models / login.php>
< h2>登入< br />< br /> (发布/管理媒体资源)< / h2>
< input type =emailclass =homepagename =user_email2id =user_email2placeholder =Emailmaxlength =50required />
< div class =errormsgid =errormsg6>< / div>
< div class =errormsgid =errormsg7>< / div>
< input type =submitname =loginid =loginvalue =Submit>
< div class =errormsglastid =errormsg8>< / div>
< div class =homeforgotpassword>< a href =忘记密码class =忘记密码连结>忘记密码< / a>< / div>
< / form>
< / div>

用于验证的jquery / ajax如下所示:

  $(document).ready(function()
{
/ * -----------------登录验证全局变量----------------- * /
var user_email2 =;
var user_password2 =;
var user_emailajax2 = ;
var user_mobileajax2 =;

var emailformat = new RegExp(/ ^ [+ a-zA-Z0-9 ._-] + @ [a-zA-Z0 -9 .-] + \。[a-zA-Z] {2,4} $ / i);

/ * -------------- ---定义验证电子邮件地址* /
var validate_email_login = function()
{
var item5 = $(#user_email2).val();
var item5 = item5 .toLowerCase();

if(item5.length< 6 || item5.length> 50)
{
$(#errormsg6)。html( ;
user_email2 =;
}
else
{
$(#errormsg6)。html( )
user_email2 = item5;
if(!emailformat.test(item5))
{
$(#errormsg6)。html(错误的电子邮件格式)
user_email2 =;
}
else
{
$(#errormsg6)。html()
user_email2 = item5;
$ .ajax(
{
type:'POST',
url:'classes / validatelogin.php?f = 1',
data:user_email2 = + item5,
成功:函数(msg)
{
if(msg ==exists)
{
$(#errormsg6)。html ();
user_emailajax2 = item5;
}
else if(msg ==ok)
{
$(#errormsg6)。html (电子邮件不存在);
user_emailajax2 =;
}
}
});
}
}
}

/ * -----------------定义验证密码* /
var validate_password_login = function()
{
var item5 = $(#user_email2)。val();
var item5 = item5.toLowerCase();

var item6 = $(#user_password2)。val();
if(item6.length< 8 || item6.length> 20)
{
$(#errormsg7)。html(Password:8-20 Characters)
user_password2 =;
}
else
{
$(#errormsg7)。html()
user_password2 = item6;
$ .ajax(
{
method:POST,
url:classes / validatelogin.php?f = 2,
data:user_email2 = + item5 +& user_password2 =+ item6,
成功:函数(msg)
{
if(msg ==WrongPw)
{
$(#errormsg7)。html(Wrong Password);
user_mobileajax2 =;
}
else if(msg ==CorrectPw)
{
$(#errormsg7)。html();
user_mobileajax2 =item6;
}
}
});


$ b $ * -----------------运行函数* /
$(#user_email2 ).on('focusout',validate_email_login);
$(#user_password2)。on('focusout',validate_password_login);
$(#login)。on('click',validate_email_login);
$(#login)。on('click',validate_password_login);
$ b $ * -----------------停止提交* /
$(#login)。click(function()
{
if(user_email2 ==|| user_password2 ==|| user_emailajax2 ==|| user_mobileajax2 ==)
{
$(# (请填写所有字段(正确))
返回false;
}
else
{
返回true;
}
});
});

如果没有错误,表单会一次点击提交,但如果出现错误和这些错误(根据验证规则),然后提交按钮需要两次点击才能提交​​。



已经尝试了以下的事情:

重命名 $(#login)。click(function() to $(#login)。on ,function()



$(#login)。trigger(click); code> - 在返回true之后并且返回true之前

$(#login).click(); - 在返回true和返回true之前

< input type =buttonname =loginid =login value =Submit> - 更改提交按钮



我试过这个解决方案(它没有工作,结果是两个一样的所需点击...)

$ $ p $ code $ $(document).ready(function()
{
/ * -----------------登录验证全局变量----------------- * /
var user_email2 =;
var user_password2 =;
var user_mobileajax2 =;
var emailformat = new RegExp(/ ^ [+ a-zA-Z0-9 ._-] + @ [a-zA-Z0-9 .-] + \。[a-zA-Z] { 2,4} $ / I);
/ * -----------------定义验证密码* /
var validate_password_login = function()
{
// Set延期对象
var def = $ .Deferred();
var item5 = $(#user_email2)。val();
var item5 = item5.toLowerCase();
var item6 = $(#user_password2)。val();
if(item6.length< 8 || item6.length> 20)
{
$(#errormsg7)。html(Password:8-20 Characters);
user_password2 =;
//不是有效的密码,所以拒绝延期的
def.reject();
}
else
{
$(#errormsg7)。html();
user_password2 = item6;
$ .ajax(
{
method:POST,
url:classes / validatelogin.php?f = 2,
data:user_email2 = + item5 +& user_password2 =+ item6
})
.done(函数(msg)
{
if(msg ==WrongPw)
{
$(#errormsg7)。html(Wrong Password);
user_mobileajax2 =;
//服务器表示PW错误,因此拒绝此
def.reject();
}
else if(msg ==CorrectPw)
{
$(#errormsg7)。html();
user_mobileajax2 =item6;
//看起来我们是有效的,所以我们可以解析这个
def.resolve();
}
.fail(function()
{
//服务器端发生错误,因此必须拒绝
def.reject();
});
}
//我们返回promise
return def.promise();

-----------------运行函数* /
$(#user_password2)。on('focusout', validate_password_login);
//提交处理函数
$('form [name =loginform]')。on('submit',function()
{
//设置($ validate_password_login())
.done(function()
{
//完成意味着成功!
return true ;
})
.fail(function()
{
//失败显然是失败的
return false;
});
});
});


解决方案

我没有完全复制整个登录设置,但我做了一个快速假的测试,通过将ajax.success更改为ajax.error并使用错误的url触发错误,然后在错误内部,我将msg变量设置为等于发送信号的字符串有效的回复,表单不需要两次提交。



这样,再加上仔细看看代码,我会猜测这个问题是一种种族您的点击处理程序是这样设置的:

  

$('#login')。on('click',validate_email_login);
$(#login)。on('click',validate_password_login);
$(#login)。click(function(){...});

最后一个处理程序的内部是代码检查字符串以查看结果是否有效的地方。但是,到达那里时,那些先前的ajax请求可能尚未完成加载,并且这些字符串可能尚未重置。您可以在该函数中添加一些console.logs,以查看这些值是什么并进行确认。



因为这些ajax调用是异步的,所以您将不得不等待它们完成后才能检查表单是否有效。您正在寻找的是承诺 Deferreds



我建议将它重构为如下所示:


  1. 在两种验证方法中设置Deferred。
  2. 删除#login点击处理程序并将所有内容移动到提交表单的处理程序。
  3. 在表单的提交处理程序中调用验证方法时使用 $。
  4. 快速代码示例:

      // Move提交处理程序
    $('form [name =loginform]')。on('submit',function(){
    //设置$ .when中的验证方法
    $ .when(validate_email_login(),validate_password_login())
    .done(function(){
    //完成表示成功!
    返回true;
    })
    .fail(function(){
    //失败显然是失败的。
    返回false;
    });
    });

    除了jQuery文档,乍一看,这看起来像是另一个很好的例子和资源一切的解释: http://jqfundamentals.com/chapter/ajax-deferreds 。我认为这些东西最接近底层。



    快速设置某种验证方法的外观(未经测试):

      var validate_password_login = function(){
    //设置延迟对象
    var def = $。递延();
    var item5 = $(#user_email2)。val();
    var item5 = item5.toLowerCase();
    var item6 = $(#user_password2)。val(); (item6.length< 8 || item6.length> 20){
    $(#errormsg7)。html(Password:8-20 Characters);


    user_password2 =;
    //不是有效的密码,所以拒绝延期的
    def.reject();
    } else {
    $(#errormsg7)。html();
    user_password2 = item6;
    $ .ajax({
    method:POST,
    url:http://www.google.com,
    data:user_email2 =+ item5 + (&#;
    ))
    .done ).html(Wrong Password);
    user_mobileajax2 =;
    //服务器表示PW错误,因此拒绝此
    def.reject();
    } else if(msg ==CorrectPw){
    $(#errormsg7)。html();
    user_mobileajax2 =item6;
    //看起来我们是所以我们可以解决这个
    def.resolve();
    }
    })
    .fail(function(){
    //服务器上出错了所以不得不拒绝
    def.reject();
    });
    }

    //我们返回promise
    return def.promise();
    }


    i have an html form which which does jquery/ajax validations.

    following is the html form...

    <div class="box3">
        <form method="post" name="loginform" action="models/login.php">
        <h2>LOGIN<br /><br /> (Post/Manage Property)</h2>
            <input type="email" class="homepage"  name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
            <div class ="errormsg" id ="errormsg6"></div>
            <input type="password" class="homepage"  name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
            <div class ="errormsg" id ="errormsg7"></div>
            <input type="submit" name="login" id="login" value="Submit">
            <div class ="errormsglast" id ="errormsg8"></div>
            <div class="homeforgotpassword"><a href="forgot-password" class="forgotpasswordlink">Forgot Password</a></div>
        </form>
    </div>
    

    the jquery/ajax for validation is as follows

    $(document).ready(function()
    {
        /* ----------------- Login Validations Global Variables -----------------   */
        var user_email2 = "";
        var user_password2 = "";
        var user_emailajax2 = "";
        var user_mobileajax2 = "";
    
        var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
    
        /* ----------------- Define Validate Email */
        var validate_email_login = function()
            {
                var item5 = $("#user_email2").val();
                var item5 = item5.toLowerCase();
    
                if (item5.length < 6 || item5.length > 50)
                {
                    $("#errormsg6").html("Email : 6 - 50 Characters");
                    user_email2 = "";
                }
                else
                {
                    $("#errormsg6").html("")
                    user_email2 = item5;
                    if (!emailformat.test(item5))
                    {
                        $("#errormsg6").html("Wrong Email Format")
                        user_email2 = "";
                    }
                    else
                    {
                        $("#errormsg6").html("")
                        user_email2 = item5;
                        $.ajax(
                        {
                            type: 'POST',
                            url: 'classes/validatelogin.php?f=1',
                            data: "user_email2=" + item5,
                            success: function(msg)
                            {
                                if (msg == "exists")
                                {
                                    $("#errormsg6").html("");
                                    user_emailajax2 = item5;
                                }
                                else if (msg == "ok")
                                {
                                    $("#errormsg6").html("Email Does Not Exist");
                                    user_emailajax2 = "";
                                }
                            }
                        });
                    }
                }
            }
    
        /* ----------------- Define Validate Password */
        var validate_password_login = function()
            {
                var item5 = $("#user_email2").val();
                var item5 = item5.toLowerCase();
    
                var item6 = $("#user_password2").val();
                if (item6.length < 8 || item6.length > 20)
                {
                    $("#errormsg7").html("Password : 8-20 Characters")
                    user_password2 = "";
                }
                else
                {
                    $("#errormsg7").html("")
                    user_password2 = item6;
                    $.ajax(
                    {
                        method: "POST",
                        url: "classes/validatelogin.php?f=2",
                        data: "user_email2=" + item5 + "&user_password2=" + item6,
                        success: function(msg)
                        {
                            if (msg == "WrongPw")
                            {
                                $("#errormsg7").html("Wrong Password");
                                user_mobileajax2 = "";
                            }
                            else if (msg == "CorrectPw")
                            {
                                $("#errormsg7").html("");
                                user_mobileajax2 = "item6";
                            }
                        }
                    });
                }
            }
    
        /* ----------------- Run Functions */
        $("#user_email2").on('focusout', validate_email_login);
        $("#user_password2").on('focusout', validate_password_login);
        $("#login").on('click', validate_email_login);
        $("#login").on('click', validate_password_login);
    
        /* ----------------- Stop on Submit */
        $("#login").click(function()
        {
            if (user_email2 == "" || user_password2 == "" || user_emailajax2 == "" || user_mobileajax2 == "")
            {
                $("#errormsg8").html("Please Fill All Fields (Correctly)")
                return false;
            }
            else
            {
                return true;
            }
        });
    });
    

    if there are no errors then the form submits in one click, however if there are errors and these errors are then rectified (as per validation rules) then the submit button requires two clicks to submit.

    Have tried the following things

    Renaming $("#login").click(function() to $("#login").on( "click", function()

    $("#login").trigger("click"); - after return true and before return true

    $( "#login" ).click(); - after return true and before return true

    <input type="button" name="login" id="login" value="Submit"> - changing the submit to button

    I tried this solution (it did not work, result was the same two clicks required... )

    $(document).ready(function()
    {
        /* ----------------- Login Validations Global Variables -----------------   */
        var user_email2 = "";
        var user_password2 = "";
        var user_mobileajax2 = "";
        var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
        /* ----------------- Define Validate Password */
        var validate_password_login = function()
        {
            // Set up the deferred object
            var def = $.Deferred();
            var item5 = $("#user_email2").val();
            var item5 = item5.toLowerCase();
            var item6 = $("#user_password2").val();
            if (item6.length < 8 || item6.length > 20)
            {
                $("#errormsg7").html("Password : 8-20 Characters");
                user_password2 = "";
                // Not a valid password so reject the deferred
                def.reject();
            }
            else
            {
                $("#errormsg7").html("");
                user_password2 = item6;
                $.ajax(
                    {
                        method: "POST",
                        url: "classes/validatelogin.php?f=2",
                        data: "user_email2=" + item5 + "&user_password2=" + item6
                    })
                    .done(function(msg)
                    {
                        if (msg == "WrongPw")
                        {
                            $("#errormsg7").html("Wrong Password");
                            user_mobileajax2 = "";
                            // The server said the PW was wrong, so reject this
                            def.reject();
                        }
                        else if (msg == "CorrectPw")
                        {
                            $("#errormsg7").html("");
                            user_mobileajax2 = "item6";
                            // Looks like we are valid so we can resolve this
                            def.resolve();
                        }
                    })
                    .fail(function()
                    {
                        // Something went wrong on the server side, so have to reject
                        def.reject();
                    });
            }
            // We return the promise
            return def.promise();
        }
        /* ----------------- Run Functions */
        $("#user_password2").on('focusout', validate_password_login);
        // Move to submit handler
        $('form[name="loginform"]').on('submit', function()
        {
            // Set up the validation methods inside $.when
            $.when(validate_password_login())
                .done(function()
                {
                    // Done means success!
                    return true;
                })
                .fail(function()
                {
                    // And fail is obviously a fail.
                    return false;
                });
        });
    });
    

    解决方案

    I didn't fully replicate this with an entire login set up, but I did do a quick fake to test by changing the ajax.success to ajax.error and using a bad url to trigger the error, then inside of the error, I set the msg variable equal to the string that signals a valid response and the form did not require two submits.

    That, coupled with giving the code a closer look, I'm going to guess the issue is a sort of race condition due to the ajax calls.

    Your click handlers are set up like this:

    $("#login").on('click', validate_email_login);
    $("#login").on('click', validate_password_login);
    $("#login").click(function() { ... });
    

    Inside of that last handler is where the code checks the strings to see if the results are valid. However, by the time it gets to there those previous ajax requests may have not finished loading and those strings probably have not been reset yet. You can add some console.logs in that function to see what those values are and confirm.

    Because those ajax calls are asynchronous you are going to have to wait for them to finish before you can check that the form is valid. What you are looking for are Promises and Deferreds.

    I would suggest refactoring it into something like this:

    1. Set up a Deferred in both of your validation methods.
    2. Remove the #login click handlers and move everything into a submit handler for the form.
    3. In the submit handler of the form call the validation methods using $.when.

    Quick code example:

    // Move to submit handler
    $('form[name="loginform"]').on('submit', function() {
        // Set up the validation methods inside $.when
        $.when(validate_email_login(), validate_password_login())
         .done(function() {
            // Done means success!
            return true;
         })
         .fail(function() {
            // And fail is obviously a fail.
            return false;
         });
    });
    

    In addition to the jQuery docs, at a glance, this looks like another good resource for examples and an explanation of everything: http://jqfundamentals.com/chapter/ajax-deferreds. I think the stuff that is most like what you have is towards the bottom.

    A quick set up of what one of the validation methods might look like (untested):

    var validate_password_login = function() {
        // Set up the deferred object
        var def = $.Deferred();
        var item5 = $("#user_email2").val();
        var item5 = item5.toLowerCase();
        var item6 = $("#user_password2").val();
    
        if (item6.length < 8 || item6.length > 20) {
          $("#errormsg7").html("Password : 8-20 Characters");
          user_password2 = "";
          // Not a valid password so reject the deferred
          def.reject();
        } else {
          $("#errormsg7").html("");
          user_password2 = item6;
          $.ajax({
            method: "POST",
            url: "http://www.google.com",
            data: "user_email2=" + item5 + "&user_password2=" + item6
          })
          .done(function(msg) {
              if (msg == "WrongPw") {
                $("#errormsg7").html("Wrong Password");
                user_mobileajax2 = "";
                // The server said the PW was wrong, so reject this
                def.reject();
              } else if (msg == "CorrectPw") {
                $("#errormsg7").html("");
                user_mobileajax2 = "item6";
                // Looks like we are valid so we can resolve this
                def.resolve();
              }
           })
           .fail(function() {
              // Something went wrong on the server side, so have to reject
              def.reject();
            });
        }
    
        // We return the promise
        return def.promise();
    }
    

    这篇关于jquery Ajax表单需要2次点击才能提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆