1

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.

1ef
  • 13
  • 3
  • 9
    because it is asynchronous. You are making 4 calls and it is a race to which one returns first. – epascarello Aug 01 '22 at 15:51
  • 1
    https://api.jquery.com/jquery.when/ – epascarello Aug 01 '22 at 15:53
  • 1
    Might help: https://stackoverflow.com/questions/34510/what-is-a-race-condition – freedomn-m Aug 01 '22 at 15:54
  • 2
    `contentType: 'application/json; charset=utf-8'` is nonsense. You're making a GET request. There's no body at all, let alone one encoded as JSON. – Quentin Aug 01 '22 at 15:54
  • 2
    `alert` is blocking - so if you put in the loop (not in the .then) then you're saying "send this, wait for user, send next, wait for user" rather than "send all of these at the same time". – freedomn-m Aug 01 '22 at 15:55

1 Answers1

1

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" />
dave
  • 62,300
  • 5
  • 72
  • 93
  • It may not matter in this case but beware that this still doesn't guarantee sequential execution of requests (one after the other). These requests will still run in parallel. – Mauro Aguilar Aug 01 '22 at 16:22