简体   繁体   English

如何在提交表单之前等待ajax验证完成?

[英]How to wait for ajax validation to complete before submitting a form?

Having a problem where the form submits before the validateUsername function has a chance to complete the username check on the server-side. 表单在validateUsername函数之前提交的问题有可能在服务器端完成用户名检查。

How do I submit the form only after the validateUsername function completes? 如何在validateUsername函数完成后提交表单? Hope this is clear... 希望这很清楚......

form.submit(function(){
    if (validateUsername() & validateEmail() & validatePassword()) {
        return true;
    } else {
        return false;
    }
});         

function validateUsername(){            
    usernameInfo.addClass("sign_up_drill");
    usernameInfo.text("checking...");
    var b = username.val();
    var filter = /^[a-zA-Z0-9_]+$/;     
    $.post("../username_check.php",{su_username:username.val()},function(data) {
        if (data=='yes') {
            username.addClass("error");
            usernameInfo.text("sorry, that one's taken");
            usernameInfo.addClass("error");
            return false;           
        } else if (!filter.test(b)) {
            username.addClass("error");
            usernameInfo.text("no funny characters please");
            usernameInfo.addClass("error");
            return false;   
        } else {
            username.removeClass("error");
            usernameInfo.text("ok");
            usernameInfo.removeClass("error");      
            return true;    
        }
    });             
}   

More verbose version of Olafur's answer - The AJAX call is made and the function returns without waiting. 更详细的Olafur的答案 - 进行了AJAX调用,函数返回时无需等待。

The callback doesn't finish until you've submitted the form. 在您提交表单之前,回调不会完成。

What you should do is have the button/trigger calling the AJAX validation, and the callback should submit the form instead of returning true. 你应该做的是让按钮/触发器调用AJAX验证,回调应该提交表单而不是返回true。

The jQuery form validation plugin takes care of this for you -- I highly recommend it. jQuery表单验证插件为您解决了这个问题 - 我强烈推荐它。

Some sample code: 一些示例代码:

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true
    },
    username: {
      required: true,
      remote: {
        url: "../username_check.php",
        type: "post",
        }
      }
    }
  }
});

In jQuery there is a solution for the same. 在jQuery中有一个相同的解决方案。 I need to check if a user exists or not in my application during some JavaScript. 在某些JavaScript期间,我需要检查我的应用程序中是否存在用户。 Here is the code: 这是代码:

var pars = "username="+ username;
var some = $.ajax({url: 'AjaxUserNameExist.php',
  type: 'GET',
  data: pars,
  async: false
}).responseText;


if(some=="1") //this is value Got from PHP
{
  alert("We cannot Go");
  return false;
}

if(some=="0")
{
  alert("We can Go");
  return true;
}   

I dealt with a similar issue recently. 我最近处理过类似的问题。 Under some circumstances, pressing enter on an input field might make the form submit. 在某些情况下,在输入字段上按Enter可能会使表单提交。 I attempted to remedy this in a number of ways, and then the specifications required changed so that pressing the Enter key or Go on a device, will allow a form submission. 我试图通过多种方式解决这个问题,然后更改所需的规范,以便按Enter键或设备上的Go,将允许表单提交。 My solution was just what made sense to me at the time. 我的解决方案当时对我来说是有意义的。

var form_submit = false;

function validateInput () {

    var field_value = $('#username').val();

    $.post('validation.php', {'input': field_value }, function (d) {
        if (d.valid) {

            form_submit = true;
            $('form').submit();

        } else {

            //error message or whatever

        }
    }, 'json');

}

$('form').submit( function () {

    if ( form_submit ) {
        return true; 
    } else {
        validateInput();
        return false;
    }

});

You can't return in an AJAX call. 您无法在AJAX调用中返回。 I suggest you read this section of the jQuery FAQ. 我建议你阅读jQuery FAQ的这一部分 Specially the part about callbacks. 特别是关于回调的部分。 (the last code snippet) (最后一段代码片段)

Why dont you just use $('#yourFormId').submit(); 为什么不使用$('#yourFormId').submit(); after you have received a result from your ajax backend? 从ajax后端收到结果后?

I suggest having 我建议有

1) a hidden field in your form. 1)表单中的隐藏字段。
2) Set the value of it to 0 before you call any of the function that makes an AJAX request. 2)在调用任何发出AJAX请求的函数之前,将其值设置为0。
3) Increment the value when each of the function is successful in validating. 3)当每个功能成功验证时增加值。
4) Set some number of seconds (ie amount of time/timeout it will take to complete all AJAX requests + a few seconds) to wait before checking the value of this hidden field. 4)在检查此隐藏字段的值之前设置一些秒数(即完成所有AJAX请求所花费的时间/超时时间+几秒)。 Check if the value is 3 (if there were 3 AJAX calls for validation) and let it submit then. 检查值是否为3(如果有3个AJAX调用进行验证),然后让它提交。

I guess, it will be better to do validation when the control looses the focus. 我想,当控件失去焦点时进行验证会更好。 Enable the submit button only when all controls pass the validation. 仅当所有控件都通过验证时才启用提交按钮。

Sorry, I am not too familiar with JQuery but I will do this, if I were to use plain javascript. 对不起,我对JQuery不太熟悉,但如果我使用普通的javascript,我会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM