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

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

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 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