简体   繁体   中英

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.

How do I submit the form only after the validateUsername function completes? 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.

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.

The jQuery form validation plugin takes care of this for you -- I highly recommend it.

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. I need to check if a user exists or not in my application during some 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. 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. 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. I suggest you read this section of the jQuery FAQ. Specially the part about callbacks. (the last code snippet)

Why dont you just use $('#yourFormId').submit(); after you have received a result from your ajax backend?

I suggest having

1) a hidden field in your form.
2) Set the value of it to 0 before you call any of the function that makes an AJAX request.
3) Increment the value when each of the function is successful in validating.
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. Check if the value is 3 (if there were 3 AJAX calls for validation) and let it submit then.

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.

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