AJAX XMLHttpRequest

The XMLHttpRequest object makes AJAX possible.

XMLHttpRequest

The XMLHttpRequest object is the key to AJAX.

This object has been available since Internet Explorer 5.5 and after the release of July 2000, but before the discussion of AJAX and Web 2.0 in 2005, this object was not fully recognized.

Create XMLHttpRequest object

Different browsers use different methods to create XMLHttpRequest object.

Internet Explorer uses ActiveXObject.

Other browsers use a name called XMLHttpRequest of the JavaScript built-in object.

To overcome this problem, you can use this simple code:

var XMLHttp=null
if (window.XMLHttpRequest)
  {
  XMLHttp=new XMLHttpRequest()
  }
else if (window.ActiveXObject)
  {
  XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }

Code Explanation:

  1. First create an object that uses XMLHttpRequest as an object XMLHttp Variable. Set its value to null.
  2. Then test window.XMLHttpRequest Whether the object is available. In the new versions of Firefox, Mozilla, Opera, and Safari browsers, the object is available.
  3. If available, then use it to create a new object:XMLHttp=new XMLHttpRequest()
  4. If not available, then detect window.ActiveXObject Whether it is available. In Internet Explorer version 5.5 and higher, the object is available.
  5. If available, use it to create a new object:XMLHttp=new ActiveXObject()

Improved example

Some programmers prefer to use the latest and fastest version of the XMLHttpRequest object.

The following example attempts to load the latest version of "Msxml2.XMLHTTP", available in Internet Explorer 6, and if it cannot be loaded, it falls back to "Microsoft.XMLHTTP", available in Internet Explorer 5.5 and later versions.

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

Code Explanation:

  1. First create the object used as the XMLHttpRequest object XMLHttp Variable. Set its value to null.
  2. Create objects according to web standards (Mozilla, Opera, and Safari):XMLHttp=new XMLHttpRequest()
  3. Create objects in the Microsoft way, available in Internet Explorer 6 and higher versions:XMLHttp=new ActiveXObject("Msxml2.XMLHTTP")
  4. If an error is caught, try an older method (Internet Explorer 5.5):XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")

More information about the XMLHttpRequest object

If you want to read more about XMLHttpRequest, please visit our AJAX Tutorial.