jQuery: The Write Less, Do More JavaScript Library

AjaxQueue

From jQuery JavaScript Library

Jump to: navigation, search

This page documents some concepts and ideas for an AJAX queue plugin.

To start with, here are a few mails pasted from the discussion list:

I recently ran into a situation similar to the one shown in this screencast: http://www.phppatterns.com/stuff/latency.html

The short version: Rapidly dispatched Asynchronous Javascript requests don't always return to the client in the same order they were sent, introducing odd behavior.

In my experience, 99.9% of the time, this is not an issue. However, that 0.1% is killing me.

I wanted to start some discussion about whether this might be addressed within jQuery, how to address it, should it be a plugin, etc. I'd be happy to write one.

Additional Links on the topic: http://www.sitepoint.com/blogs/2006/11/16/race-conditions-ajax-and-sessions/ http://www.sitepoint.com/blogs/2006/02/10/ajaxlocalhost/ http://ajaxblog.com/archives/2005/06/01/async-requests-over-an-unreliable-network

Here's another great example with a solution.

http://www.cmarshall.net/MySoftware/ajax/index.html

His code is large and in charge, but looks like he's done a good job. I'm positive we could optimize this with jQuery.


You may also want to cancel Ajax requests (as is the case with autocomplete), but I don't know if you can do that with jQuery. Maybe something like:

 $.ajax({
   type: "GET",
   url: "autocomplete.php",
   queue: "autocomplete",
   cancelExisting: true
 })

Which would cancel an existing request in the 'autocomplete' queue if a new request is made and the old request hasn't finished.

Maybe also a function to stop all current requests? $.stopAjax(function(){alert("All Ajax requests stopped")}) or those in a queue $.stopAjax("autocomplete", function(){alert("autocomplete Ajax requests stopped")})


I've been bothered about this also. The simplest approach is to do what TCP/IP does - number each response, and ignore all but the latest response.

To elaborate: since you can have multiple, parallel, independent streams of Ajax going on, you need to number those also - call them ports. For each port, you take only the response with the highest number.

Eg: Response (processed) port=1; response=2;

Response (ignored) port=1; response=1;

Response (processed) port=2; response=1;

Last, once we're handling this, we may as well kill all old requests once a newer response has come in - this cuts down on server load.