Archive for June 2, 2007

JavaScript: Creating XMLHttpRequest object for Ajax

Posted in JavaScript, Software, Web, internet, programming on June 2, 2007 by Joey

To create an XMLHttpRequest object to be used in JavaScript for an Ajax application:

try {
var objXHR = new XMLHttpRequest();
} catch (e) {
try {
var objXHR = new ActiveXObject(‘Msxml2.XMLHTTP’);
} catch (e) {
try {
var objXHR = new ActiveXObject(‘Microsoft.XMLHTTP’);
} catch (e) {
document.write(‘XMLHttpRequest not supported’); }
}
}

The first try attempts to initialize XMLHttpRequest using the native XMLHttpRequest object. This object is present in Mozilla, Internet Explorer 7 and most other modern browsers.

Since the XMLHttpRequest object was not available in Internet Explorer prior to version 7, the next two try blocks are necessary. There are two because the libraries in Internet Explorer versions differ with two implementations of how to initialize an XMLRequestRequest object.

So that is basically how an XMLHttpRequest object is created in JavaScript for use in an Ajax application. What is the next step? JavaScript XMLHttpRequest open Method: Calling a URL in Ajax