Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

307
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda