PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] Why is AJAX in for loop executing in wrong order

 September 08, 2022     ajax, for-loop, javascript, jquery, php     No comments   

Issue

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.


Solution

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



Answered By - dave
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing