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.