JavaScript表单验证问题 - 必须单击提交两次

时间:2014-08-04 12:55:34

标签: javascript php jquery ajax validation

验证的JavaScript代码 - https://freedigitalphotos.net/images/js/judd-validate.js

我们的网站上有一些新的表单,它们有客户端JavaScript验证。

当用户" defocuses"来自表单字段。验证是AJAX(检查有效用户名的数据库等)和JavaScript(检查字段不是空白,或包含预期数据)的组合。

用户必须单击两次表单提交按钮才能发送表单。似乎第一次点击是触发字段验证但不提交表单。单击第二次成功完成表单。

转到 - https://freedigitalphotos.net/images/recover_password.php 在电子邮件字段中输入arifkpi@gmail.com,然后立即点击提交。再次注意,第一次单击只是验证输入,使用AJAX检查电子邮件地址是否在数据库中。需要再次点击。

我想解决这个问题,所以只需点击一下即可完成所有工作。

1 个答案:

答案 0 :(得分:1)

不是在focustout事件上调用Ajax验证,而是可以在按钮的click上调用它,如果Ajax返回true结果,那么submit以编程方式形成。请参考几个示例代码行:

Html Part:

<form method="post" id="registration_form" name="registration_form" action="register.php">
  EmailId: <input type="text" id="email_id" name="email_id">
  <label class="error" for="username" id="globalErrorUsername"></label>
  Username: <input type="text" id="username" name="username">
  <label class="error" id="globalErrorEmail"></label>
  <button type="button" id="register_btn" name="register_btn">Register</button>
</form>

Js Part:

$("#register_btn").click(function() {
    //.valid function is useful when you are using jquery Validate library for other field validation
    if ($('#registration_form').valid()) {
        var email_id = $('#registration_form').find('#email_id').val(),
            username = $('#registration_form').find('#username').val();
        $.ajax({
            beforeSend: function() {
                $('#globalErrorUsername').html('');
                $('#globalErrorEmail').html('');
             }, //Show spinner
            complete: function() {  },
            type : 'post',
            url : 'check-user-existence.php',
            dataType :'json',
            data : 'email_id=' + email_id + '&username=' + username,
            success:function(response) {
                if(response.success == 1) {
                    //submit the form here
                    $("#registration_form").submit();
                } else if (response.error == 1) {
                    if(response.details.username != undefined) {
                        $('#globalErrorUsername').show();
                        $('#globalErrorUsername').html(response.details.username);
                    }
                    if(response.details.email_id != undefined) {
                        $('#globalErrorEmail').show();
                        $('#globalErrorEmail').html(response.details.email_id);
                        $('#email_id').focus();
                    } else {
                        $('#username').focus();
                    }

                }
            }
        });
    } else {
        return false;
    }
    return false;
});