Wednesday, February 15, 2006

XMLHttpRequest : Key to AJAX

Thanks to the XMLHttpRequest, web clients can retrieve and submit XML data for interim updates without reloading the page.

Creating XMLHttpRequest Object

Creating the XMLHttpRequest object depends on the browser. For Safari and Mozilla , we can use :
var req = mew XMLHttpRequest();

For IE , we use
var req = new ActiveXObject("Microsoft.XMLHTTP");

Hence we need to write a generic function to intialize the object
// Initialize the XMLHttpRequest object depending on type of browser
function Initialize()
{
try
{
req=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
req=null;
}
}

if(!req&&typeof XMLHttpRequest!="undefined")
{
req=new XMLHttpRequest();
}

}

Object Methods

Of all supported methods by XMLHttpRequest, the most important one for us is the "open()" method.

The syntax of Open method is
open("method","URL",AsncFlag,"username","pwd");

The first parameter is HTTP method you intend to use , that is "GET" or "POST". The second parameter as name suggest, is the URL. The third parameter is optional and is a flag which controls wether incomign transaction should be handled asynchronosly. The default value is "true"