Five Common Ajax Anti-Patterns

Based on his experience working with Ajax developers in the field, Jack Herrington has written in-depth about common pitfalls in Ajax code, calling out five specific problems he sees often enough to consider anti-patterns, summarized here:

Polling on a timer when you don't need to. While JavaScript has timer functionality (via window.setInternval() usually), it should be used sparingly. Animations are a valid use, but other uses should be carefully checked. One definite red flag is the use of a timer to watch for a request to finish. Callbacks should be used instead of polling.

Not inspecting the return results in the callback. When using the processReqChange()callback on the XMLHTTPRequest object, the readyState and status fields of the callback argument need to be checked. The callback will often be invoked before the results are complete. Failing to check this result can cause errors if code tries to process incomplete data.

Passing complex XML when HTML would be better. Formatting XML into displayable HTML in the browser can require a lot of JavaScript, which exposes developers to more browser incompatability issues. As a rule of thumb:

As with everything, the choice between whether to process on the server or on the client depends on the demands of the job. In this case, the job was relatively simple: Put up a table of movies. If the job were more complex -- perhaps with sorting, searching, adding or deleting, or dynamic interaction in which clicking a movie brings up more information -- then I can see going with more complex code on the client. In fact, I'll demonstrate sorting on the client at the end of this article, where I talk about the counter-argument of putting too great a load on the server.

Passing XML when you should pass JavaScript code. Simply put, don't use XML when you could use JSON:

The benefits are clear. In this example, there was a 52% savings in the size of the data blob downloaded to the client by going with the JavaScript language. There's a performance increase, as well. It was 9% faster to read the JavaScript version. While 9% might not seem like a lot, just remember that this was a fairly rudimentary example. Larger blocks of data or more complex structures will require more XML parsing code, while the JavaScript code will remain unchanged.

Doing too much on the server Simple single-page functionality, like sorting a table, can be more quickly and efficiently done in JavaScript rather than on the server.