0

I cant understand what I'm doing wrong on this one. I've got a while loop running an AJAX function to get data from a PHP file for the amount of people selected from a dropdown.

$(document).on('change', '#attendingCount', function() {
  $(".person-container").html("");
  var amount = $(this).val();
  var i = 0;

  while (i < amount) {
    getPerson(i);
    i++;
  }
});

getPerson(0);

function getPerson(e) {
  $.ajax({
    type: 'post',
    url: './person.php',
    data: {
      "amount": e
    },
    success: function(data) {
      $(".person-container").append(data);
    },
    error: function() {
      console.log('error');
    }
  });
}

When the result gets pumped out though, the order of them is completely random. What is it exactly I'm doing wrong?!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Andrew Gordon
  • 181
  • 1
  • 10
  • 2
    AJAX is.....wait for it....Asynchronous! There is no guarantee you'll receive responses in the order you request them in. – Jay Blanchard Dec 04 '17 at 15:13
  • 2
    I wouldn't use a AJAX call to get every single person. Instead, return a JSON array with the amount of users you want, then load them in your container. – GreyRoofPigeon Dec 04 '17 at 15:14
  • 2
    You're not doing anything inherently wrong, the issue is because the AJAX call is asynchronous. This means that while you may send the requests in order, they may come back in a completely different one, depending on how long it takes to transmit the data, how long the server takes to process each request and how long the response takes to transmit. If you *have* to receive the request back in order, you'll need to chain them one after the other. Better yet, send all the data in a single request. – Rory McCrossan Dec 04 '17 at 15:15
  • 2
    Use the loop to build an array of people you want returned, then send that to the server and let it return one ordered list that you can append to your container. – SteveB Dec 04 '17 at 15:15
  • Possible duplicate of [Javascript - AJAX request inside loops](https://stackoverflow.com/questions/22621689/javascript-ajax-request-inside-loops) – Jared Smith Dec 04 '17 at 15:40
  • Thanks all for your responses, i'll have a gander at it tonight as im currently at work. just thought ide ask this morning. I kinda just assumed that the while loop would make it pump out in order as the requests are put in that way. but I guess not! i'll take a look at changing it without ajax, probably easier to just hide the DIV with CSS. thought ide be clever but never mind. – Andrew Gordon Dec 04 '17 at 16:49

1 Answers1

0

AJAX works in an asynchronous way, not necessarily the first request you send is going to return data first, that's the problem here. Doing an AJAX call in a while loop is not the best solution.