Learning AJAX - The XMLHttpRequest Object
(Page 2 of 4 )
JavaScript has a built-in XMLHttpRequest object for requesting web pages. You can use that for Firefox, Safari, and Opera. For Internet Explorer use ActiveXObject. But it is different for IE 5.0 and IE 6.0+. The following code creates an XMLHttpRequest.
var req;
try
{
// Firefox, Opera, Safari
req = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
Here we are first trying to get create a XMLHttpRequest using the built-in function. If it fails we will try using ActiveXObject("Msxml2.XMLHTTP"), and if that fails as well we will try ActiveXObject("Microsoft.XMLHTTP"). If all of these fail, we will alert the user that his browser does not support AJAX. Use ActiveXObject("Msxml2.XMLHTTP") for Internet Explorer 6 and above. Use ActiveXObject("Microsoft.XMLHTTP") for Internet Explorer 5.
Now we have the XMLHttpRequest as a variable req. We now can request a server side page using the GET or POST method.
req.open("GET","somedata.php");
req.send(null);
Here we try to get somedate.php using the HTTP GET method.
We now wait for the state change of this request.
req.onreadystatechange = handleResponse;
function handleResponse(){
if(req.readyState == 4 && req.status == 200){
//returned text from the PHP script
var response = req.responseText;
}
}
The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State | Description |
0 | The request is not initialized |
1 | The request has been set up |
2 | The request has been sent |
3 | The request is in process |
4 | The request is complete |
If the readyState value is 4, it indicates the request is complete, and a status value of 200 means a successful response. Some possible values for request status are 4xx or 5xx. These values of the request status means the request failed due to a wrong URL or authentication problem or for some other reason. As mentioned earlier the response can be either in String or XML format. To get a string value use responseText. To get an XML value for the response, you need to use responseXML.
Next: The Complete File >>
More JavaScript Articles
More By Mamun Zaman