Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda