简体   繁体   中英

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?

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

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

onsubmit="return validate(this);"

in 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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