Ajax not working: some common sense rules

Ajax not working: how many times did you notice that something went wrong with your web application? Many times, to be honest. A couple of hours ago I was trying to post a link on my Facebook status. I got nothing, because when I clicked on the "Share" button, I got a blank page. Quite frustrating. Sometimes you get nothing, other times you get the infamous "Service Unavailable" or "Check your connection". In the worst case scenario, the web page makes your browser hang, as I saw happening many times on Gmail.

First rule: don't trust Ajax completely – As I said in an earlier post, Ajax is still an immature standard, because it lacks of a fine control over your HTTP connection. What we got so far? We have the XMLHttpRequest object that has a very limited set of methods and properties. With the XHR object you can actually get only server status codes (HTTP codes), but you have no control on the effective responsiveness of your connection. A common workaround to this problem is to use the setTimeout() and setInterval() global methods to avoid leaks in your connection by setting, say, a given amount of time before closing a slow connection. That's fine, but the XHR object has no methods to do this per se.

Second rule: don't rely only on Ajax – I mentioned earlier an example taken from Facebook. Facebook doesn't provide an alternate way to use its contents. If you open Facebook with a textual browser, such as Lynx, you get a message saying "we're not cool enough to support your browser" or something. That's freaky. Without providing a fallback mechanism, it's more likely that your web application will fail completely when Ajax doesn't work.

Third rule: avoid the overuse of Ajax libraries -– Ajax libraries are a really useful thing. I often use many Ajax methods of jQuery to write my Ajax code, but I have to say that this kind of approach has its limits. The fact is that all libraries tend to hide the details of an Ajax connection by encapsulating them in their own wrappers. When something goes wrong, it's harder to spot the line of code that causes trouble, because everything lies inside the library. Sometimes it's better to write our own code to create an Ajax connection, especially when we stumble on some obtuse browser bug with an Ajax library.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.