The right way to create an XMLHttpRequest Object

Microsoft announced that they were going to support the native XMLHttpRequest object in IE7. This changes how you should do Ajax calls ...

With IE5.0 - 6.0 the only option for Ajax calls is one of the ActiveX objects (Msxml2.XMLHTTP, Microsoft.XMLHTTP, etc), however with IE7 the will support the window.XMLHttpRequest object.

Why are they doing this? Is the ActiveX control not good enough? Are there bugs that can not be fixed in the ActiveX control?

I think the reality is that Microsoft would like to deprecate ActiveX completely. It can't be done today without breaking things, but it makes good sense in the future. Microsoft are already changing things in that direction; IE6 in Windows Server 2003 runs with ActiveX disabled and in Vista installing new Active objects has been made harder.

Depending on how the ActiveX Ajax object is retired, and how bugs are fixed in the various IE7 implementations we need to be using the native XMLHttpRequest object in preference to the ActiveX objects starting now.

So, wrong code:

var xhr;
if (window.ActiveXObject) {
  xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
}

This is wrong because it will be using the ActiveX control in IE7 in preference to the native XMLHttpRequest object.

Instead we should be doing this:

var xhr;
if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
  xhr = new ActiveXObject("Msxml2.XMLHTTP");
}

I just checked with the DWR code which gets this right (purely by fluke - I can't claim fore-thought on this one) but a number of other big implementations get it the wrong way around.

Comments

Comments have been turned off on old posts