Now with Ajax!

I finally got around to polishing off an Ajax version of Bob vs Sam, just as a little tech demo to make sure I’ve got the concepts under control. It’s something I had been putting off for a while. But now that it’s done, there’s no page reloading or re-rendering, and the Bob vs Sam performance is significantly better, thus alleviating concerns which were often keeping me up at night. Just in case you may not have been around for the beginning of Bob and Sam’s gripping Peano-inspired donnybrook, they’re racing… to infinity… and they need your help.

The actual coding was pretty straightforward. If you go to the web toy - open it in another tab or something, go ahead - and View Source, you’ll see that most of the intelligence is in the “client,” written in Javascript and embedded in the recalculate() function up in the <head> element of the HTML. There are some gotchas.

If you retrieve the same URL each time, with no unique arguments, Internet Explorer will read the results from its cache, which is no good at all. Note the “If-Modified-Since:” header being set right before the send(”") call; this is just a way to make it explicit to IE that it should really get a fresh copy of /cgi-bin/getbobsam.cgi every time. Firefox, my preferred browser, doesn’t assume it can get the results of a XMLHttpRequest::open(”GET”…) out of the cache, which is a Bad Thing when the document you’re retrieving works more like a mathematical function. Either approach is justifiable, but (as usual) it’s frustrating that they can’t simply agree.

Centering the table by using the “margin-left:auto; margin-right:auto” style? What a gross hack! But many sites agreed that it was the least awful way to get the job done, and it beats using <center> tags, I guess.

Opera gave me zero trouble. It agrees with Firefox on most things and IE on the rest. Yay Opera! Unfortunately, the JavaScript required for even this level of Ajax appears to be beyond Pocket Internet Explorer and Opera Mobile 8 (or perhaps they don’t fire onClick events). Boo Smartphone browsers! Edit 17 July 2006: Actually, it appears that the problem is that Pocket IE only supports the IE3.02 DOM, which is worthless. Opera’s documentation for Mobile is uncharacteristically poor, so I still don’t know precisely what is keeping that from working; it may well be that it has an incomplete JavaScript implementation, or that it has an archaic or nonstandard DOM implementation.

When you get back your results, in your onreadystatechange handler, note that there won’t be anything in reponseText if the document you’re GETting has its type set to text/html in its header. You have to access its contents via responseXML and the DOM methods. The converse is also true - you can’t get anything out of responseXML unless the type is so set.

At some point, I’ll have to write this up into a tutorial. It goes on my list of things to do in my Copious Free Time.

Leave a comment