JavaScript: Coping with Client Server Conflicts

One of the things that worries me about writing Ajax apps is how easy it is for the client and the server to get out of sync. Open up the app in two different browsers, and it's easy to play havoc. Even if you implement Comet, all you have to do is temporarily lose Internet connectivity to go out of sync.

One way to cope with this problem is by using the "409 Conflict" HTTP status code. If the client makes a request, and the server knows that the client is working with stale state, it can return a "409 Conflict". In my own case, if the client makes an Ajax request, and the server returns a "409 Conflict", the client will reload the current page. It's not perfect, but it's a simple, effect, and easily-implemented strategy.

Here's how to return a "409 Conflict" in Rails:

render :text => "Your browser is out of sync with the server. Please reload the page.",
:status => "409 Conflict"
Here's how you can handle a "409 Conflict" if you are making an Ajax request with jQuery:
var HTTP_CONFLICT = 409;

type: "POST",
url: "/some/url",
data: data,

// If we get an HTTP_CONFLICT, it means our data is stale. Reload the
// page. To test this functionality, use two tabs in your browser.
error: function(xhr, textStatus, errorThrown) {
if (xhr.status == HTTP_CONFLICT) {