簡體   English   中英

表單提交問題之前的jQuery Ajax驗證

[英]Jquery ajax validation before form submit issues

我正在嘗試使用ajax驗證驗證碼,即使正在提交返回值錯誤的表單,我的錯在哪里?

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

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
        }
    });
}

問題是檢查是異步的。 您可以取消表單提交,然后在驗證請求返回時提交表單。

試試這個

在HTML

onsubmit="return validate(this);"

在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