Home > Blockchain >  JQUERY foreach appending PHP script out of order
JQUERY foreach appending PHP script out of order

Time:04-04

I have this ajax function that loads a php script for each item in an array and then appends it to an html tag. The issue is that the scripts are appending out of order. How do I preserve the order of the objects?

jQuery(function($) {
  $.getJSON('apiUrl.com', function(response) {
    $.each(response.data, function(key, val) {
      $.get("phpFile.php", {
        id: val.id,
        title: val.title,
        img_url: val.images.jpg.image_url
      }, function(html) {
        $("#elementToLoadPhpFile").append(html);
      });
    });
  });
});

CodePudding user response:

All of your $.get requests are being called in parallel. This results in a race condition where the order is not maintained. Think of it as first comes, first served.

To preserve the order wrap each request in a Promise and collect all these promises in a single array. Pass the array to Promise.all to wait for all requests to finish.

Whenever all requests are done you'll get an array which has the same order in which all requests are made. Loop over this array to append the values of each request to the page.

jQuery(function($) {
  $.getJSON('apiUrl.com', function(response) {
    const requests = response.data.map(val => new Promise((resolve, reject) => {
      $.get("phpFile.php", {
        id: val.id,
        title: val.title,
        img_url: val.images.jpg.image_url
      })
      .done(html => resolve(html))
      .fail((xhr, textStatus, errorThrown) => reject(errorThrown));
    }));

    Promise.all(requests).then(responses => {
      responses.forEach(html => {
        $("#elementToLoadPhpFile").append(html);
      });
    });
  });
});
  • Related