Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain order of requests when making several ajax callbacks

Tags:

jquery

ajax

I'm looping through several items and making an ajax request for each of them (using jQuery). I want them to execute independently, but populate into the DOM in the order they were called, not the order they are returned (for some reason some requests are taking longer than others). Any tips on the best practice for this type of thing?

like image 898
Chris Avatar asked Dec 06 '10 21:12

Chris


2 Answers

Well the results can come back in any undefined order, they are asynchronous and subject to the vagaries of the internet and servers.

What you can do is deal with the problem in the same way TCP does over UDP. You use sequence identifiers.

Keep a sequence identifier going, and increment it every time you send out a request. As requests come back, check them off in order and only process them as they come in. Keep a list of what has returned with the data in order, and have a routine fire to check that list after each update to it. When the first expected is in, it should process the whole list down to the first gap.

Bare in mind that you could lose a request, so a suitable timeout before you ignore a given sequence identifier would be in order.

like image 53
Orbling Avatar answered Sep 20 '22 12:09

Orbling


The answer to this ended up being a jQuery plugin called ajaxManager. This did exactly what I needed:

https://github.com/aFarkas/Ajaxmanager

like image 34
Chris Avatar answered Sep 22 '22 12:09

Chris