Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
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);
      });
    });
  });
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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);
      });
    });
  });
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda