Dealing with ajax has become so easy and high-level that it is pretty easy to forget about the details. A nice habit to get into when dealing with an ajax-heavy frontend is to manage the event listeners and connections that a user can initiate.
Something simple to remember is that you can’t rely on your requests to complete FIFO because your requests are getting routed across multiple processes/machines that may or may not be under load. Alot of users are rather click-happy (my mom still double-clicks links) which can lead to problems with content that was requested on the first click being loaded after the content from the most recent click.
In the past I have always included sequence numbers as request ID’s and then have the server include the request ID it is responding to in the JSON response. This gives the event handlers some context of the response it just received in relation to the most recent action the user has performed on the page.
This works well, but sometimes you just want to throw out any response that is not in response to the most recent request. This is where the abort() method is useful.
var current_conn;
function getSome() {
if(current_request) {current_request.abort();}
current_request = $.get('/events',
{ team : "Ramrod" },
function(resp) { alert(resp); }
);
}
If you need to, you could use the sequence number approach and create a response queue or other more complex solution. Here are a few neat ideas as well…
Amazon Web Services
3 Comments
One method I am a fan of is to just prevent the user from getting click happy. Disable the submit button once it is clicked. This is built into Rails with the :disable_with option on the submit tag.
The only drawback to disabling the element is that if the remote call fails to go through for some reason there is no way to re-submit the request (unless your user is comfortable using Firebug). Obviously you could setup handlers to detect the failure and re-enable but most developers won’t go to that trouble.
typobug
var current_conn;
should be
var current_request
I currently cannot cancel xmlhttprequest $.ajax() returns
wonder why… Maybe < ?php ignore_user_abort( 1 ) ?>
< ?php ignore_user_abort( 1 ) ?>