As the use of XML and web services is increasing day by day, it is good to connect an HTML page with XML, with the help of that we can get interim updates so easily without reloading the page. It is possible due to the XMLHttpRequest object, which is responsible for retrieving and submitting the XML data directly from the client side. It relies on Document Object Model (DOM) to convert the retrieved XML data into HTML.
Microsoft first implemented the XMLHttpRequest object in IE 5 for Windows as an ActiveX object. Afterward Mozilla and Apple's Safari also implemented in their own style.
XMLHttpRequest object facilitates the web developer a lot because with the help of this object you can update the page with new data without reloading the page, communicate with server in the background, request and receive data from the web server.
Creating an XMLHttpRequest object.
We can create an instance of the XMLHttpRequest in most of the modern popular browsers, and in the old versions of the browsers we need to create an object of ActiveXObject.
var xmlobj=new XMLHttpRequest ();
var activeobj=new ActiveXObject("Microsoft.XMLHTTP");
How to use an XMLHttpRequest Object and Handle the server response:
We need to create an XMLHttpRequest, after that we will use few important functions like:
- onreadystatechange property: After submitting the request to the server, we need to store the response from the server. onreadystatechange property stores the response from the function which process the server.
- readystate property: readystate property holds the
state of the server response, every time readystate property change ,
onreadystatechange function executes. Possible values and their meaning are
State The Request is: 0 Not initialized 1 Has been set up 2 Has been sent 3 In process 4 Is complete
- responseText property: The data sent back from the server is stored and retrieved later with the help of responseText property.