XMLHTTPRequest
Normally,
when you have to do some operation at server side, say some database oriented
operation like any of well known CRUD (create, retrieve, update and delete)
operations. You will submit whole form/page to server and get a whole new page
from server to re paint on your browser. In very few, situations that are ok
but mostly its not required at all.
Suppose,
you have header image, left navigation bar, footer links like (contact us,
about us, privacy policy…) and in middle of page some textboxes and one submit
button.
You
fill those textboxes and want to save given information in database and then
clear the textboxes. Sounds good!
But
what happen, when you click on submit button, all the contents on the web page
will go to the server like header, footer, navigation bar and your textboxes.
Purpose of submit button was to save information given in database then why
header, navigation bar and footer being sending to server. I guess, it doesn’t
make sense until they are needed to update.
So,
if you want to send your specific controls data only to server and want to
update those controls at browser side, then here comes “XMLHTTPRequest” object.
XMLHTTPRequest
is JavaScript object which used to send request to server and receive response
from server. Through XMLHTTPRequest, you can communicate with server
synchronously and asynchronously as well. It depends upon your need of
communication. If your next step(s) relying on server response then you need
synchronous communication pattern but if don’t want to keep user on wait, don’t
want to freeze User Interface (UI) at user side and can proceed without having
result on next line of call then you can use asynchronous communication pattern.
Before
rushing towards implementation I would like to specify methods and properties
of XMLHTTPRequest object
Method | Description |
abort() | This
method aborts the current HTTP request. The object will be returned to the
UNINITIALIZED state, and the open method must be called next |
getAllResponseHeaders() | This
method retrieves the values of all the HTTP headers as a string. Each
name/value pair is separated by a combination carriage return/linefeed
character. The results of this method are only valid after the send method
returns successfully. |
getResponseHeader() | his
method retrieves the value of the specified HTTP header as a string from the
response body. The results of this method are only valid after the send
method returns successfully. The full list of header variables that can be
queried can be discovered with the getAllResponseHeaders method. |
open() | This
method initializes a Microsoft.XMLHTTP request, and specifies the method, URL
and authentication information for the request. |
send() | This
method sends an HTTP request to the server and receives a response |
setRequestHeader() | This
method specifies the name of an HTTP header. The 'bstrHeader' parameter is a
string that should be the actual text of the HTTP header without any colon.
The 'bstrValue' parameter should be the string value of the header. If a
header of the same name already exists, it is replaced. |
Property | Description |
onreadystatechange | This
property is write-only, and specifies the event handler for the |
readyState | This
property represents the state of the request. |
responseBody | This
property represents the response entity body as an array of unsigned bytes. |
responseStream | This
property represents the response entity body as an IStream |
responseText | This
property represents the response entity body as a string. |
responseXML | This
property represents the response entity body as parsed by the MSXML XMLDOM
parser. |
status | This
property is read-only and represents the HTTP status code returned by a
request. It is only valid after the send method returns successfully |
statusText | This
property is read-only and represents the HTTP response line status as a BSTR
value. It is only valid after the send method returns successfully. |
readyState Property
readyState property of XMLHTTPRequest object contains status of the response. Whenever state changes, “onreadystatechange” event fire.
Following is a table of readyState states and description
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 |
To
clear concept and usage of XMLHTTPRequest, I would like make some real time
example with code and comments and to make easy coding steps I would like to
mention first pseudo code.
Problem
Here
we suppose page is divided into several sections (header, footer, navigation
bar and some widgets, portlets same as in any portal like Google IG,
PageFlakes). We just need to get weather condition of specific city. If we
press any button to send request to server to get weather condition of that
city and send us in response then all other widgets, portlets and sections of
page will also go to server (which I guess is unnecessary in this scenario) so
request object will be heavy unnecessarily and yes take more time.
Solution
Use
XMLHTTPRequest to send specific city, whose weather condition is required
asynchronously so other parts of the page remain interactive for the user.
Pseudo Code
- Create
XMLHTTPRequest object
- Call Open
method of created object and pass parameters
- Call send
method to send request to server
- Get response
from server by created object property named responseText
Implementation step by step
Simple HTML code
<div>
<input type="text" id="txtCity"/>
<input type="button"id="btnGetWeather"value="Get
Weather" onclick="GetWeather();"/>
</div>
<div id="dvWeather"></div>
JavaScript Code
<script type="text/javascript">
function GetWeather()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
//get user entered city name
var city = document.getElementById('txtCity').value;
//first parameter is to specify Method either GET or POST
//second parameter is URL of server, where you want to send
request
//Third parameter would define either communication pattern
is synchornous(false) or asynchornous(true)
xmlHttp.open("GET","GetWeather.aspx?City=" + city,true);
//GetWeather.aspx is include in sample, which is
intermediate between your request and web service.
//send request to server according to parameters
xmlHttp.send();
//defining function to call whenever xmlhttp state
changes
xmlHttp.onreadystatechange=function()
{
//if request has been entertained and response is returned
from server
if(xmlHttp.readyState==4)
{
//show contents of the response using
responseText property of xmlHttp obj
document.getElementById('dvWeather').innerHTML
= xmlHttp.responseText;
}
}
}
</script>
GetWeather.aspx
is an Application Proxy as web service which we are consuming is not on the
same server from which you are making request is not allowed to consume. That’s
why, I used asp.net based page and consume web service using .net and return
response of that web service to XMLHTTP object.
GetWeather.aspx.cs
code
public partial class GetWeather :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
//clear
reponse
Response.Clear();
//Namespace.Class object = new Namespace.Class();
Weather.Weather weather = new Weather.Weather();
//Call web method (GetWeather) and pass parameter (city
name)
//and write result in response to return to xmlhttp object
Response.Write(weather.GetWeather(Request.QueryString["City"]));
Response.End();
}
}
I
have added web service in my application using “Add web Reference” and wrote
code to call that web service. I hope it’s easier than Rocket Science.
ConclusionXHR is made possible communication between client side and server really easy and quick. It brings performance but being using quite abusively as its less secure medium of communication and could have security loop holes if not used properly.