Fakejax – Bastardizing Ajax
I’ve recently come upon two Ajax-like techniques that violate the letter of the Ajax law, but also make things a lot easier.
Technique #1: Forget the Callback
All of the Ajax tutorials and frameworks I’ve looked at use the callback approach. The user clicks something, an Ajax request is sent, the server does some processing, and then a response invokes a callback on the client side to update the UI.
This certainly seems reasonable assuming one or more of the following is true:
- The server is really fast, so the UI appears responsive
- The operations in question are more atomic, so the server has less to do.
- The server is doing something non-trivial. It’s not just setting a value. So really the client couldn’t do this logic even if they wanted to.
- The operation is vital and requires confirmation (e.g. bank transaction)
I think some Ajax developers take the callback approach for granted without considering whether their application satisfies any of these criteria. For example, let’s say that the user is able to add a tag to an object in your application. The standard Ajax approach would be:
- User clicks “Add Tag”
- After some cheesy transition effect, a field appears
- User types in the tag name and clicks submit
- Browser invokes Ajax request
- User waits a short, but noticable, time
- Ajax response comes in as a success
- UI is updated showing the new tag
What I’m suggesting is that for non-essential and non-complex operations, you just ditch the callback and update the UI at request time. What’s the worst that can happen? You invoke the request, update the UI, but the server actually throws an error. No big deal — either the server retries the request automatically or the tag actually doesn’t get created even though the user thinks it did.
Of course, the worst case scenario can be pretty jarring for users. It looks as though the tag was created but it actually wasn’t. But I do believe that there is a class of use cases for which this is acceptible. Where the side-effects of an incorrect UI update are minor and the risk of a server-side error are low.
Technique #2: Wholesale DIV Replacement
I week or two ago, I read this article on using Ajax with Struts. I’ve been using Ajax with Struts for about 4 months, but I wanted to see how other people were doing it.
The article had a really neat idea. I’m not sure if this approach is already common knowledge, but it was new to me.
Anyway, maybe everybody already knows about these things, but both struck me as interesting and potentially useful. There’s a pretty clear drawback to the second one (overhead of more data and more server-side processing), but I’m all in favor of keeping the interactivity in the client but the code on the server.