XMLHttp object
The XMLHTTP in IE and XMLHttpRequest object in other browsers function similarly. So the only difference for cross browser support is during creation of the objects.
Here is how you could create a request object that will work on both browsers:
function getXmlHttp()
{
try
{
// Return an XMLHttpRequest object for most browsers
return new XMLHttpRequest();
}
catch(exception)
{
try{
// For newer IE browsers
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch(exception)
{
try{
//For older IE browsers
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(exception)
{
//Could not create XMLHttp object
return null;
}
}
}
}
The code is a bit big, but once you code it, you don't have to do it again. It is a one time affair, which can be reused in all Ajax code. Once you get the XMLHTTP object or XMLHttpRequest object, you need to register a callback function. To do that, you need to register a call back function onreadystatechange. The state of the request can be obtained by checking the readyState property of the object. This property can have the following values.
Value | Meaning |
---|---|
0 | Request not initialized |
1 | Request has been set up |
2 | Request sent |
3 | In process |
4 | Complete (Response obtained) |
Once the response has been received, the status property of the XMLHTTP or XMLHttpRequest has to be checked. If everything is fine, the status code shoule be 200. If not, it indicates some problem. So, the outline of our basic Ajax call is like this:
var httpRequest = getXmlHttp();
httpRequest.onreadystatechange = callBackFunction;
// or you could directly give the function here:
// httpRequest.onreadystatechange = function () {
// ... function body ...
// }
The callback function should have been already defined. An example callBackFunction will be:
function callBackFunction()
{
if(httpRequest.readyState == 4 && httpRequest.status == 200)
{
// ... Code to handle the response ...
}
}
To actually make a call, you first call the open method. It takes 3 parameters: the HTTP method to be used (usually GET or POST), the URL to send the request to, and a boolean indicating wether you want synchronous or asynchronous mode. A value of true will make the call asynchronous.
Once these things are set up, call the 'send' method. For the GET method, send(null) will be called, and for POST method, it will contain a string representing the data to be sent. Data in GET method is appended to the URL.