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?!

6
  • 2
    AJAX is.....wait for it....Asynchronous! There is no guarantee you'll receive responses in the order you request them in. Commented Dec 4, 2017 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. Commented Dec 4, 2017 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. Commented Dec 4, 2017 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. Commented Dec 4, 2017 at 15:15
  • Possible duplicate of Javascript - AJAX request inside loops Commented Dec 4, 2017 at 15:40

1 Answer 1

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.

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.