1

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);
      });
    });
  });
});
2
  • "Out of order" implies some sort of sort order? The response will always be however the data was formed from the server. So, what is the "sort order" you desire? What is your server-side code returning in terms of "sort order"? Commented Apr 3, 2022 at 20:31
  • Ahh, this is AJAX so client side may not render in same order you prefer, due to the 2nd ajax call. I see now. Commented Apr 3, 2022 at 20:32

1 Answer 1

2

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 come, 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);
      });
    });
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.