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

192
Visualizações
Why is AJAX in for loop executing in wrong order

javascript:

var numbers = [0, 1, 3, 5];
for (let k = 0; k < numbers.length; k++) {
   let x = numbers[k]
   l = $.ajax({
      type: 'GET',
      url: 'body.php',
      data: {'x': x},
      contentType: 'application/json; charset=utf-8',
      }).then(function(res) {
         $("#products").append(res);
      })
}

php:

<?php 
session_start();
$x = $_GET['x'];
?>
<h5><?php echo $produkt;?></h5>

And it appends it everytime in different order, for example 0 3 1 5 or 1 5 0 3 etc. but when I add to javascript alert(), it goes in right order every time.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Because it is asynchronous. You can create an array of all of the promises and then use Promise.all to get them in order:

// Just a fake jquery ajax that returns promises
let $ = {
    ajax(props) {
        return new Promise((resolve) => setTimeout(() => resolve(`<h5>${props.data.x}</h5>`), Math.floor(Math.random() * 500)));
    }
}

var numbers = [0, 1, 3, 5];

const p = numbers.map((x) => {
    return $.ajax({
        type: 'GET',
        url: 'body.php',
        data: {'x': x},
        contentType: 'application/json; charset=utf-8',
    })
});

Promise.all(p).then((responses) => {
    responses.forEach((response) => {
        document.getElementById('products').innerHTML += response;
    });
});
<div id="products" />

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