Maintain request order when making multiple ajax callbacks

I iterate over several elements and make an ajax request for each of them (using jQuery). I want them to be executed independently, but populated in the DOM in the order in which they were called, and not in the order in which they were returned (for some reasons, some requests take longer than others). Any best practice tips for this type of thing?

+7
jquery ajax
source share
4 answers

The answer was a jQuery plugin called ajaxManager. This did exactly what I needed:

https://github.com/aFarkas/Ajaxmanager

+4
source share

Well, the results can be returned in any order undefined, they are asynchronous and prone to the vagaries of the Internet and servers.

What you can do is solve the problem just like TCP over UDP. You are using sequence identifiers.

Keep the sequence ID and increment it every time you submit a request. When requests are returned, check them in order and process them only as they arrive. Keep a list of what returned with the data in order, and you have a regular fire to check this list after each update. When the first is expected, it should process the entire list before the first break.

Mention that you may lose the request, so the appropriate timeout before you ignore this sequence identifier will be fine.

+8
source share

You can send all objects of the result of success to the queue. Have the index that was sent with the original request, and constantly check this queue for the next index.

But in general, browsers only allow two concurrent ajax requests, so just send the next ajax request for the success of the previous request.

This is where the code starts:

var results = {}, lastProcessedIndex = 0; var totalLength = $('a.myselector').each(function(el, index){ $.ajax({ url: $(this).attr('href'), success: function(result){ results[index] = result; // add to results object } }); }).length; var intervalId = setInterval(function(){ if(results[lastProcessedIndex]){ // use object lastProcessedIndex++; } else if(totalLength == lastProcessedIndex){ clearInterval(intervalId); } }, 1000); // every 1 second 
+1
source share

I will take a hit in the dark with this, but it can help. Perhaps you can create a global buffer array, and then when AJAX returns, you can add the result to the buffer. Then you can set up a timer that checks the contents of the buffer at startup. If they are fine, he will output it accordingly.

0
source share

All Articles