Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
JQUERY foreach appending PHP script out of order

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);
      });
    });
  });
});
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
      });
    });
  });
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!