Home > Enterprise >  Why is AJAX in for loop executing in wrong order
Why is AJAX in for loop executing in wrong order

Time:08-02

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.

CodePudding user response:

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

  • Related