Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
jQuery Wait for Ajax Before Submitting Form

I have three Ajax functions I would like to complete before a form is submitted, but they are also triggered on submit.

What would be the best way to force jQuery to wait until all Ajax functions complete before the form is sent? My code is as follows:

$('form[name="regForm"]').on('submit', function() {
    ajaxFuncOne();
    ajaxFuncTwo();
    ajaxFuncThree();
});
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

  1. First stop the submission (using e.preventDefault();),
  2. Then wrap your ajax calls in a $.when() function,
  3. Then submit the form.

Don't forget to unbind the on('submit') listener functionality before submitting, else you will end up in an infinite loop (as submit() will be triggering on('submit'), which will be triggering submit(), and so forth).

Like so:

$('form[name="regForm"]').on('submit', function(e) {

    e.preventDefault();

    $.when(
        ajaxFuncOne();
        ajaxFuncTwo();
        ajaxFuncThree();
    ).done(function(){
        $('form[name="regForm"]').unbind('submit').submit();
    });
});

See https://api.jquery.com/jquery.when/ for more information on $.when().

about 4 years ago · Santiago Trujillo Report

0

Define a counter variable for tracking how many ajax functions have succeeded, in the scope accessible to all functions. Let's assume it's called c. Then, prevent submission if it is not equal to three. Disable the button to avoid further clicks.

$('form[name="regForm"]').on('submit', function() {
  if(c < 3) {
    e.preventDefault();
    $(this).attr('disabled','disabled');
    ajaxFuncOne();
    ajaxFuncTwo();
    ajaxFuncThree();
  }
});

Then call the following in each success handler.

function track() {
  if(++c == 3) $('form[name="regForm"]').submit();
}

Only when all three have succeeded, will the form be submitted.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!