Understanding XmlHttpRequest
Posted On January 16, 2007 by Rose Mary filed under Internet
Ever wanted your web applications to run like desktop applications? Ajax seems to be the answer to millions of developers who will answer the question in the affirmative. The biggest advantage of using Ajax technologies is that data can be manipulated without having to render the entire page again in the web browser. This allows web applications to respond more quickly to many types of user interaction and avoid repeatedly sending unchanged information back and forth across the network.
You will be surprised that most technologies used in the Ajax portfolio have existed for long. When these technologies are used strategically, you can create web applications that run like the ones you have on desktop.
In this tutorial series, we will explore some of the methods and technologies that are used to build Ajax-based web applications and portals.
In this article explore XmlHttpRequest, a JavaScript object that is fuelling Ajax programming revolution. XmlHttpRequest is nothing new and has been around for some time. To be precise, XmlHttpRequest was first introduced in Internet Explore 4.0 by Microsoft as an ActiveX object. Today, almost all popular browsers, from Firefox to Safari, have a native object.
What does this object do?
HTTP requests can be made and responses received, completely in the background, without the user experiencing any visual interruptions using JavaScript’s XmlHttpRequest object. This means that a web developer need not worry about his application becoming slower because of traversals from the client browser to the web server. The user will stay on the same page and he/she will not notice that scripts might request pages or send data to a server in the background. In other words, by using the XMLHttpRequest object, a web developer can change a page with data from the server after the page has loaded.
The XmlHttpRequest object is not yet a W3C standard, but it is expected to become one sooner than later.
Client-side scripting developers have choices for implementing an XmlHttpRequest using two methods:
1. If you have a Microsoft Internet Explorer 5.0 and above, use ActiveX object –
var http=new ActiveXObject("Microsoft.XMLHTTP"); and
2. If the browser is Mozilla or Safari, you can create a JavaScript object –
var xmlhttp=new XMLHttpRequest()
Methods and Properties of XmlHttpRequest
The XmlHttpRequest object has a few methods and properties that are useful in Ajax applications. In the rest of this article, we will explore more of these details. Tables 1 and 2 list the methods and properties of the object.
Table 1: Methods
| Method | Description |
abort() | Cancels the current request. |
getAllResponseHeaders() | Returns the complete set of http headers as a string. |
getResponseHeader("headername") | Returns the value of the specified http header. |
open("method","URL",async,"uname","pswd") | Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "PUT" (use "GET" when requesting data and use "POST" when sending data (especially if the length of the data is greater than 512 bytes. The URL parameter may be either a relative or complete URL. The async parameter specifies whether the request should be handled asynchronously or not. ‘true’ means that script processing carries on after the send() method, without waiting for a response. ‘false’ means that the script waits for a response before continuing script processing. |
send(content) | Sends the request. |
setRequestHeader("label","value") | Adds a label/value pair to the http header to be sent. |
Table 2: Properties
| Property | Description |
Onreadystatechange | An event handler for an event that fires at every state change. |
ReadyState | Returns the state of the object: 0 = uninitialized |
ResponseText | Returns the response as a string. |
ResponseXML | Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties. |
Status | Returns the status as a number (e.g. 404 for "Not Found" or 200 for "OK"). |
StatusText | Returns the status as a string (e.g. "Not Found" or "OK"). |
Let us write a simple program to illustrate XmlHttpRequest. Though this program does not illustrate the power of XmlHttpRequest, it gives you an idea about what you can do with the program.
Consider, for example, the code given in code 1. This is a simple program that will read an html file and print some of details of the file in a table within the HTML file.
The code works on a simple theme. It creates a variable xmlhttp and assigns it as an ActiveXObject or as a JavaScript object, depending on the browser. Once it validates the browser, it calls a function called func_Change.
The fun_Change calls some xmlGttpRequest properties and prints inside the table. The concept is simple. I have uploaded the JavaScript embedded file and sample file (ron.html) on http://www.developeriq.com/mag/xmlhttp1.html.
Check out the code for yourselves.
Code 1
<html>
<head>
<script type="text/javascript">
var xmlhttp
function loadXMLDoc(url)
{
// code for Mozilla, etc.
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=func_Change
xmlhttp.open("HEAD",url,true)
xmlhttp.send(null)
}
// code for IE
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
if (xmlhttp)
{
xmlhttp.onreadystatechange=func_Change
xmlhttp.open("HEAD",url,true)
xmlhttp.send()
}
}
}
function func_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
document.getElementById('Table').innerHTML="This file was last modified on: " + xmlhttp.getResponseHeader('Last-Modified') + " The file'S ResponseHeaders are :" + xmlhttp.getAllResponseHeaders()
}
else
{
alert("Problem retrieving data:" + xmlhttp.statusText)
}
}
}
</script>
</head>
<body onload="loadXMLDoc('ron.html')">
<div id="Table" style="border:1px solid black;height:400;width:400"></div>
</body>
</html>
Check the web link mentioned in the above paragraph to get a result as in the figure.
When the XMLHttpRequest object operates within a browser, it adopts the same-domain security policies of typical JavaScript activity. This has some important implications that will impact your application.
First, on most browsers supporting this functionality, the page that bears scripts accessing the object needs to be retrieved via http: protocol, meaning that you will not be able to test the pages from a local hard disk (file: protocol) without some extra security issues cropping up, especially in Mozilla and IE on Windows. In fact, Mozilla requires that you wrap access to the object inside UniversalBrowserRead security privileges. IE, on the other hand, simply displays an alert to the user that a potentially unsafe activity may be going on and offers a chance to cancel.
Second, the domain of the URL request destination must be the same as the one that serves up the page containing the script. This means, unfortunately, that client-side scripts cannot fetch web service data from other sources and blend that data into a page. Everything must come from the same domain.
