
In an exclusively Ajax application it can be difficult for a user to determine when their connection to the server has dropped. For example, we at Pathfinder use an excellent internal tool to keep track of our time, and the primary screen in it provides a lot of Ajax-y fields. But if, say, I disconnect my laptop, plug in at home, and forget to connect to our VPN, I can waste quite a lot of time and energy putting in information without realizing it isn’t being sent to the server at all.
To fix this problem is a little less obvious than it might seem at first glance.
Prototype provides a callback for its Ajax.Request method called onFailure. It is only activated when the response code is not in the 20x range, or if is not 0. This second bit puzzled me for a bit: if the Ajax request can’t hit the server, then 0 is returned and onSuccess is triggered, even though the request was obviously not successful.
Then I realized that perhaps some Ajax programmers have their server return nothing (which is translated by Ajax.Request to 0) on a success and an error message on a failure. You’d figure that a 20x should be a success and everything ELSE should be a failure, since in a Rails app a success will always return a 20x, but who knows…
This is the code I used to solve this problem.
<%= text_area_tag "notes", nil,
nblur => "$('spinner').show();
#{remote_function :url => {
:controller => "controller",
:action => "update"},
:with => "'notes=' + escape(this.value)",
:failure => "$('connection_warning').show();",
:success => "if (request.status == 0) {$('connection_warning').show();} else {$('notes').highlight();}"}"
:rows => 5, :cols => 30,
:class => "description_entry" %>
By ensuring the response code isn’t 0, you can manually catch errors in the so-called “success” message, and provide an attractive fall-through should your server go offline or your user become disconnected.
As a bonus, you can use this same method to warn the user if their JavaScript is disabled: merely hide the connection_warning div with a JavaScript snippet, which won’t be run if the page doesn’t have JavaScript enabled. Thus a user without JavaScript won’t expect the Ajax interactions to work for them.

[...] Agile Ajax » Catching Ajax Errors with Prototype and Rails » Pathfinder Development [...]