flXHR and chained Ajax calls

getify | Ajax, flXHR, flensed | Sunday, March 22nd, 2009

So, this is just a quick post to share some information which was worked out recently in an email thread with a flXHR user. Because it’s probably a somewhat common pattern (albeit, mostly for more complex Ajax apps), I figured it would be helpful to share the information here, just in case anyone else runs up against similar issues.

flXHR has a feature called instancePooling, which is very helpful for performance/efficiency improvement reasons, especially with pages that make multiple Ajax requests. The way it does this is to keep around instantiated references of flXHR in a “pool”, and when a new instantiation is requested, if an available instance in the pool is idle and ready (that is, it’s already been used and is in readyState = 4), then it will reuse that instance (and reconfigure it as necessary) instead of creating a whole new one.

There was a bug fixed in 1.0.3 regarding flXHR’s ability to fully reconfigure a reused instance. So, if you’ve tried that type of thing prior to upgrading to 1.0.3, you should upgrade to get the expected behavior.

Anyway, this feature is almost universally necessary when doing Ajax calls with frameworks like jQuery, Dojo, Prototype, etc, because these frameworks tend to “throw away” XHR instances after single use, but with flXHR, it’s better to keep them around to avoid the “penalty” of instantiation on subsequent requests. So, rather than try to modify the way the frameworks work, flXHR makes this transparent with the opt-in “instancePooling” configuration option. I would estimate in probably 99% of all Ajax applications, this is the option you would want to keep memory-usage and instantiation times down. Unless you specifically know better, I would recommend *always* using it.

Now, as the title of this post suggests, there is a common pattern for a lot of medium-to-high complexity Ajax apps where the author of a page may need to “chain” Ajax calls — that is, make one Ajax call, and then upon completion of the first one, make another Ajax call from the response handler of the first.

It is when you combine these two concepts that a devious little “issue” creeps in. I’ll try not to go into lots of gory detail here, but the bottom line is, if you make an Ajax call from a response handler of a previous Ajax call, and you have instancePooling turned on, a race condition exists with the way framework code works which will cause issues, most notably that the handler may not get properly called on your second “chained” request, even though the full response does get back to the browser.

Read on to find out the details and how to fix it.

Bookmark and Share

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.