14 February, 2007

workaround to make AJAX calls on Internet Explorer 6

I have found a nice alternative to the traditional try catch method to make AJAX calls work on every browser. Place the following code on top of your Javascript script.
if (!window.XMLHttpRequest) {
window.XMLHttpRequest = function() {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}

This hack defines a function called XMLHttpRequest if XMLHttpRequest doesn't exist natively on the browser.
With this method, you can make AJAX calls with 'new XMLHttpRequest()' even on IE 6 or 5.5.
var ajax_call = new XMLHttpRequest();
...


UPDATE : Thanks to comments on Ajaxian, I added the "window." prefix to the declaration of the XMLHttpRequest function in order to work properly on IE 6 and not redefineing the XHR native object on IE 7.

6 comments:

Anonymous said...

I'm no AJAX expert, but is this a simple, elegant and genious as it looks? Why hasn't this been done before, or has it? If it hasn't a lot of people should be saying "d'oh!" right now :)

Sunny said...

d'oh!

JT said...

Does this break IE7's implementation by re-writing? I'm sorry I haven't tested directly to see; just thought I'd ask.

Travis said...

Could this not be taken a step further and done like:

XMLHttpRequest = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : XMLHttpRequest;

Or even shorter and be:

XMLHttpRequest = XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');

Nicolas Faugout said...

jt, yes it does on IE 7. If not enabling ActiveX on IE 7 is a concern for you, then don't use that code, otherwise, you can use it since ActiveX are of course still part of IE 7.

travis, you cannot do that. The aim here is to define once for all the XMlHttpRequest function. In your example, you have a function on one hand (XMLHttpRequest) and a pointer to an instance of an ActiveX object (new ActiveXObject('Microsoft.XMLHTTP')) on the other hand. That's not compatible.

Alkot said...

But what happens if none exist ?
This case is quite rare, but exists.