XML HTTP object

Sunday, October 31, 2010

XMLHttpRequest (XHR) is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script The data might be received from the server as XML text or as plain text. Data from the response can be used directly to alter the DOM of the currently active document in the browser window without loading a new web page document. The response data can also be evaluated by the client-side scripting. For example, if it was formatted as JSON by the web server, it can easily be converted into a client-side data object for further use.
XMLHttpRequest has an important role in the Ajax web development technique. It is currently used by many websites to implement responsive and dynamic web applications. Examples of these web applications include Gmail, Google Maps, Facebook, and many others.


Internet Explorer on Windows, Safari on Mac OS-X, Mozilla on all platforms, Konqueror in KDE, IceBrowser on Java, and Opera on all platforms including Symbian provide a method for client side javascript to make HTTP requests. From the humble begins as an oddly named object with few admirers, it's blossomed to be the core technology in something called AJAX .
The Object makes many things easier and neater than they other would be, and introduces some things that were otherwise impossible such as HEAD requests to see when a resource was last modified, or to see if it even exists. It makes your scripting options more flexible allowing for POST requests without having the page change, and opens up the possibility of using PUT, DELETE etc. These methods are increasingly used to provide richer Web Applications like G-Mail that use lower bandwidth and offer snappier user interaction.

Why XML HTTP Request object?

Whilst the object is called the XML HTTP Request object it is not limited to being used with XML, it can request or send any type of document, although dealing with binary streams can be problematical in javascript

What is AJAX?

AJAX, an acronym for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.

Creating the Object

Creating an instance of the XMLHttpRequest.object is important for Ajax. It differs for browsers.

For Safari and Mozilla:
var XmlHttp = new XMLHttpRequest();


For Internet Explorer:
var XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");


The object reference returned by both constructors is to an abstract object that works entirely out of view of the user. Its methods control all operations, while its properties hold, among other things, various data pieces returned from the server.

Object Methods

Instances of the XMLHttpRequest object in all supported environments share a concise, but powerful, list of methods and properties. The following table shows the supported methods and their jobs.


Common XMLHttpRequest Object Methods

Method
Description
abort()
Abort the current request
getAllResponseHeaders()
Get the complete set of headers (labels and values) as a string
getResponseHeader("headerLabel")
Get the string value of a single header label
send(content)
Transfers the request, optionally with postable string or DOM object data
setRequestHeader("label", "value")
Sets a label/value pair to the header to be sent with a request

Example for Creating the XMLHTTP Object
<script language="javascript">
  //Global XMLHTTP Request object
var XmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to 
//a "XmlHttp" variable  
function CreateXmlHttp()
{
 //Creating object of XMLHTTP in Internet Explorer
 try
 {
  XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch(e)
 {
  try
  {
   XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(oc)
  {
   XmlHttp = null;
  }
 }
 //Creating object of XMLHTTP in Mozilla and Safari 
 if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
 {
  XmlHttp = new XMLHttpRequest();
 }
}
</script>


The open method is to specify the attributes like URL, send method, etc.

Method
Description
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName)
open( method, URL, async, userName, password)
Assigns destination URL, method, and other optional attributes of a pending request

Two main required parameters are the HTTP method you intend for the request and the URL for the connection. For the method parameter, use "GET" on operations that are primarily data retrieval requests; use "POST" on operations that send data to the server, especially if the length of the outgoing data is potentially greater than 512 bytes. The URL may be either a complete or relative URL.
An important optional third parameter is a Boolean value that controls whether the upcoming transaction should be handled asynchronously. The default behavior (true) is to act asynchronously, which means that script processing carries on immediately after the send() method is invoked, without waiting for a response.
If you set this value to false, however, the script waits for the request to be sent and for a response to arrive from the server. While it might seem like a good idea to wait for a response before continuing processing, you run the risk of having your script hang if a network or server problem prevents completion of the transaction. It is safer to send asynchronously and design your code around the onreadystatechange event for the request object.
The following generic function includes branched object creation, event handler assignment, and submission of a GET request. A single function argument is a string containing the desired URL. The function assumes that a global variable, req, receives the value returned from the object constructors. Using a global variable here allows the response values to be accessed freely inside other functions elsewhere on the page. Also assumed in this example is the existence of a processReqChange() function that will handle changes to the state of the request object.
var requestUrl = "WebForm2.aspx" + "?SelectedCountry=" + (selectedCountry);
 CreateXmlHttp();
 
 // If browser supports XMLHTTPRequest object
 if(XmlHttp)
 {
  //Setting the event handler for the response
  XmlHttp.onreadystatechange = HandleResponse;
  
  //Initializes the request object with GET (METHOD of posting), 
  //Request URL and sets the request as asynchronous.
  XmlHttp.open("GET", requestUrl,  true);
  
  //Sends the request to server
  XmlHttp.send(null);  
 }
It is essential that the data returned from the server be sent with a Content-Type set to text/xml. Content that is sent as text/plain or text/html is accepted by the instance of the request object, however it will only be available for use via the responseText property.

Object Properties

Property
Description
onreadystatechange
Event handler for an event that fires at every state change
readyState
Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText
String version of data returned from server process
responseXML
DOM-compatible document object of data returned from server process
statusText
String message accompanying the status code

Another property is status.
This will intimate the status of the request.
Refer to the article "Dropdown Box Using AJAX" for a complete list of statuses.
I hope this article will help learners of Ajax to understand the xmlhttp object


How do I make a request?

Making a HTTP request is very simple. You tell the XML HTTP request object what sort of HTTP request you want to make and which url you want to request. Provide a function to be called when as the request is being made, and finally what, (if any) information you want sent along in the body of the request.
The following script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete, it displays the responseText to the user with an alert.
xmlhttp.open("GET", "test.txt",true);
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4) {
   alert(xmlhttp.responseText)
  }
 }
 xmlhttp.send(null)

HTTP request

The following sections demonstrate how a request using the XMLHttpRequest object functions within a conforming user agent based on the W3C Working Draft. As the W3C standard for the XMLHttpRequest object is still a draft, user agents may not abide by all the functionings of the W3C definition and any of the following is subject to change. Extreme care should be taken into consideration when scripting with the XMLHttpRequest object across multiple user agents. This article will try to list the inconsistencies between the major user agents.

The open method

The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open method. This method must be invoked prior to the actual sending of a request to validate and resolve the request method, URL, and URI user information to be used for the request. This method does not assure that the URL exists or the user information is correct. This method can accept up to five parameters, but requires only two, to initialize a request.
The first parameter of the method is a text string indicating the HTTP request method to use. The request methods that must be supported by a conforming user agent, defined by the
W3C draft for the XMLHttpRequest object, are currently listed as the following.

  • GET (Supported by IE7+, Mozilla 1+)
  • POST (Supported by IE7+, Mozilla 1+)
  • HEAD (Supported by IE7+)
  • PUT
  • DELETE
  • OPTIONS (Supported by IE7+)
However, request methods are not limited to the ones listed above. The W3C draft states that a browser may support additional request methods at their own discretion.
The second parameter of the method is another text string, this one indicating the URL of the HTTP request. The W3C recommends that browsers should raise an error and not allow the request of a URL with either a different port or ihost URI component from the current document.
The third parameter, a boolean value indicating whether or not the request will be asynchronous, is not a required parameter by the W3C draft. The default value of this parameter should be assumed to be true by a W3C conforming user agent if it is not provided. An asynchronous request ("true") will not wait on a server response before continuing on with the execution of the current script. It will instead invoke the onreadystatechange event listener of the XMLHttpRequest object throughout the various stages of the request. A synchronous request ("false") however will block execution of the current script until the request has been completed, thus not invoking the onreadystatechange event listener.
The fourth and fifth parameters are the username and password, respectively. These parameters, or just the username, may be provided for authentication and authorization if required by the server for this request.

 The setRequestHeader method

Upon successful initialization of a request, the setRequestHeader method of the XMLHttpRequest object can be invoked to send HTTP headers with the request. The first parameter of this method is the text string name of the header. The second parameter is the text string value. This method must be invoked for each header that needs to be sent with the request. Any headers attached here will be removed the next time the open method is invoked in a W3C conforming user agent.

 The send method

To send an HTTP request, the send method of the XMLHttpRequest must be invoked. This method accepts a single parameter containing the content to be sent with the request. This parameter may be omitted if no content needs to be sent. The W3C draft states that this parameter may be any type available to the scripting language as long as it can be turned into a text string, with the exception of the DOM document object. If a user agent cannot stringify the parameter, then the parameter should be ignored.
If the parameter is a DOM document object, a user agent should assure the document is turned into well-formed XML using the encoding indicated by the inputEncoding property of the document object. If the Content-Type request header was not added through setRequestHeader yet, it should automatically be added by a conforming user agent as "application/xml;charset=charset," where charset is the encoding used to encode the document.
If the user agent is configured to use a proxy server, then the XMLHttpRequest object will modify the request appropriately so as to connect to the proxy instead of the origin server, and send Proxy-Authorization headers as configured.

 The onreadystatechange event listener

If the open method of the XMLHttpRequest object was invoked with the third parameter set to true for an asynchronous request, the onreadystatechange event listener will be automatically invoked for each of the following actions that change the readyState property of the XMLHttpRequest object.
Theoretically, state changes should work like this:

  • After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1.
  • After the send method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object should be assigned a value of 2.
  • Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3.
  • Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4.
However, the major user agents are inconsistent with the handling of the onreadystatechange event listener.

For example, the following should produce four alerts: 1,2,3,4
 
xmlhttp.open("GET","somepage.xml",true);
xmlhttp.onreadystatechange = checkData;
xmlhttp.send(null);
function checkData()
{
 alert(xmlhttp.readyState);
}
In fact, some browser versions may omit state changes #1 and/or #2; if the order of the first two lines is reversed, some browsers may cause state change #1 to fire twice (or continue to omit event #2).

The HTTP response

After a successful and completed call to the send method of the XMLHttpRequest, if the server response was valid XML and the Content-Type header sent by the server is understood by the user agent as an Internet media type for XML, the responseXML property of the XMLHttpRequest object will contain a DOM document object. Another property, responseText will contain the response of the server in plain text by a conforming user agent, regardless of whether or not it was understood as XML.

0 comments:

Post a Comment