Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda