简体   繁体   English

表单提交问题之前的jQuery Ajax验证

[英]Jquery ajax validation before form submit issues

I am trying validate captcha using ajax, Even if return value false form is submitting, where is my fault? 我正在尝试使用ajax验证验证码,即使正在提交返回值错误的表单,我的错在哪里?

<form id="myid" name="formname" method="post" action="action.php"  onsubmit="return validate();">

JS JS

function validate()
{
if(document.getElementById('cap').value==''){
    alert("Please enter verification number shown in below image");
    document.getElementById('cap').focus();
    return false;
}  

var capval=document.getElementById('cap').value;

capcheck(capval).success(function (data) {
    //alert(data); not getting alert message
  if(data == "fail"){return false;} 
});
// return false; (if I use this, above alert works gives outputs either ok or fail
}
////
function capcheck(capvalue){
    return $.ajax({
        url: 'check_cap.php',
        type: 'GET',
        cache: false,
        data: {
           capid:capvalue
        }
    });
}

The problem is that the check is asynchronic. 问题是检查是异步的。 You can cancel the form submit and later when the request to validate returns, submit it. 您可以取消表单提交,然后在验证请求返回时提交表单。

Try something like this 试试这个

in html 在HTML

onsubmit="return validate(this);"

in js 在js中

function validate(form)
{
    if(document.getElementById('cap').value==''){
        alert("Please enter verification number shown in below image");
        document.getElementById('cap').focus();
        return false;
    }  

    var capval=document.getElementById('cap').value;

    capcheck(capval).success(function (data) {
      if(data != "fail") {
        form.submit(); // HERE IS THE ASYNC SUBMIT
      }
      else alert('form error: '+ data);
    });
    return false; // ALWAYS PREVENT SUBMIT ON CLICK OR ENTER
}

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

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