Most likely, though, is that our HTTP GET has finished successfully and returned with "OK" or something else. If the result is "OK", we know that we've been granted exclusive access to this article, so we can clear the warning message, enable the Save button, and set the keepAlive interval to a more reasonable rate to ensure that we maintain our exclusive access to this article.
Warning! You might think that using the same object name with a different interval value would reset the existing interval, but in Internet Explorer at least, that isn't the case. The intervals are cumulative, so you must first clear the existing interval before setting a new one.
If the result from the GET is anything other than "OK", that means (because of the PHP code we'll get to in just a few paragraphs) that this article is locked by someone else. In that case, we'll set the contents of that div to explain that the article is locked and clear the interval so we don't bother even checking any more. After all, by the time this article isn't locked anymore, the contents will likely have changed, so we want the user to refresh the page. We could actually refresh the contents automatically, and we probably will in a future version of this code.
Browser coding in general, and Ajax specifically, is fraught with timing issues, and this is one case in which I added some code to allow for them. After setting the contents of the div with the error message, I then check to make sure that the div's contents are actually what I just them to be. On rare occasions, such as when the page hasn't actually finished loading, they aren't! In that case, I just let the cycle continue, hoping things will work the next time through.
Warning! The next line of code is quite important, and before adding it I had people complaining that their entire computer systems were hanging up while editing articles. I couldn't reproduce the problem, but after digging in, I finally figured it out. Internet Explorer doesn't release the memory used by these "req" ActiveX objects, instead letting them pile up, 4K or so at a time. Eventually, Internet Explorer is using so much memory that it hangs, and when Internet Explorer hangs, problems for your Windows system are sure to follow. Bizarrely, you can't just set the event value to null, but must set it to an empty function! With req.onreadystatechange = new function(){}; in place, Internet Explorer manages memory a bit more reasonably, without any growth over time.








Article comments
1 - Aaman
I wish that Ajax book was cheaper:)
Incidentally, is this true AJAX, does the reliance on PHP and SQL not mean a new paradigm, not reliant on XML?
2 - Phillip Winn
It's still XMLHttpRequest, so all three elements of AJAX are present. The PHP and Mysql are, I think, incidental. It could as easily be anything else, or an external webservice, on the "back end."