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

124
Visualizações
Synchronously loop through AJAX calls with DOM updates

I've seen similar questions asked, but it seems that none of them are quite the same circumstance and none of the suggestions I've tried have worked. I need to call a POST from within a for loop, and I want the loop to wait for the response to complete, because it needs the previous iteration to be done before the next one can begin. I tried setting async to false for the ajax call, but that didn't work because I need to update the DOM before the beginning of the loop, after each iteration, and finally at the end, and when the http POST is synchronous it just skips right to the ajax call and locks the thread for the response. This is apparently expected JQuery behavior so I don't think anything is wrong there. So in this code example the process runs as expected but the DOM never updates, and if the async declaration is removed then the process posts all the iterations at once and they are not processed by the server correctly.

$("#form").on("submit", function(e){    
    e.preventDefault();
    $("#submit").prop("disabled",true);
    $(".loader").css("display", "block");
    var iterations = 10;
    const baseUrl = https://exampleapi.com;
    for (let i = 0; i < iterations; i++) {
        ```set post data here```
        $.ajax({
            url: baseUrl + "/endpoint",
            async: false,
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json",
        });     
        $(".progress").text("completed " + i + " iterations");      
    }
    $(".loader").css("display", "none");

Can someone help me understand what I'm doing wrong?

about 4 years ago · Juan Pablo Isaza
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