jqueryajaxformsvalidationsubmit

How to handle ajax response within a submit() in a proper way?


How would you go about to execute an ajax-call and recieve response within an submit() - codeblock? (in a proper way)

If you have a form with an submit-event, you could do like this on when validating

/* contact page */
$(".contactform").submit(function(e) {

    var companyfield = $(this).find(".companyfield").val();
    if (parseInt(companyfield) === 0 || !companyfield) {     
        return false;
    }

    return true; //Do submit form

}

Now I have to include a response from server (ajax-call) in my validation (recaptcha) but because the ajax-call is executed asynchronously the form would be submitted even if response from server isn't what is expected because function returns true before ajax-call is finished.

I have no problem with ajax-call or response but I'm not sure how achieve a return true, false without using async: false.

I basically want something like:

/* contact page */
$(".contactform").submit(function(e) {

    var companyfield = $(this).find(".companyfield").val();
    if (parseInt(companyfield) === 0 || !companyfield) {     
        return false;
    }

   var recaptchafield_is_valid = {response from server (ajax-call)}
   if (recaptchafield_is_valid  === false) {
       return false;
   }

    return true; //Do submit form

}

I've also tried $.when() but then the form is also submitted because neither true or false is set and form is submitted normally.

I've also tried using e.preventDefault() and then $(".contactform").submit() on success but then $(".contactform").submit(function(e) { get stuck in a recursive loop.


Solution

  • The way to handle this is to always return false in the submit event, then in the success event of the captcha ajax call, programatically submit the form, bypassing the submit event handler.

    $(".contactform").submit(function(e) {
        var form = this;
    
        var companyfield = $(this).find(".companyfield").val();
        if (parseInt(companyfield) === 0 || !companyfield) {     
            return false;
        }
    
        // do the ajax
        $.ajax({
            url : '...',
            success : function(){
                // if the captcha is good, submit the form
                form.submit();
            }
        });
    
        return false;
    }
    

    Note: form.submit() is calling the DOM element's submit method, not the jQuery submit handler.