If you have ever stumbled across Rasmus’s 30 second AJAX Tutorial, then you probably have the code copied, pasted, bookmarked or memorized. There are however a few limitations in this piece of code, especially with the upcoming release of IE7.
The javascript uses a small function to detect the browser.
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == 'Microsoft Internet Explorer'){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
Basically, if the browser has a User Agent of Microsoft Internet Explorer, then it is delivered an ActiveXObject rather than an XMLHttpRequest. This is fine for IE6 and below (actually quite necessary) but IE7 is set to be natively compatible with XMLHttpRequest, so we don’t want to be sending it ActiveX objects as well.
An easy way to overcome this is to use a browser compatibility check, rather than a user agent check, such as in the following example:
function createRequestObject() {
var ro;
try {
ro = window.XMLHttpRequest ? new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
ro = false;
}
return ro;
}
This checks if the browser supports XMLHttpRequest, and if it doesn’t, then and only then, it initiates the ActiveXObject. This is regardless of the user agent string being broadcast by the browser.
Obligatory warning: the above code has not been tested, and in fact has barely even been proof read, so it may not work without modification, but I am sure you will get the general gist of it. Also, Rasmus’s code has a few other failings, such as no provision for multiple xmlhttprequests, and issues with IE caching, so be warned.