Friday, September 26, 2008

What is XMLHttpRequest?

We are aware that browser understands html and sends requests to servers which are avilable remotely.

It might be ftp server or web server or any thing whose reuest/response is specific to a protocol.
For ftp servers we have communication channel called File Transfer protocol,
For web servers we have communication channel called Hyper text transfer protocol.

Protocol can be stated as the process or state of communication for exchanging infromation.
(Protocol is Simillar to a 3 volts input led can be operated with 3 volts battery but not with 230 volts Ac plug in switch board :),
I mean each protocol has its own rules for understanding, sending, retrieving data through there specific assigned ports using communication channel.)
When you consider this 'XmlHttpRequest' , it says that it is request sent by browser to a web server.



Usually we send request to webserver through browser which loads the entire page in server memory and then gets html content rendered on to the web page.
So even for transactions which are very light (click on a button displaying online voting status, etc...) it does not sounds good to reload the enttre page and loading the
results.

Xml http rquest object is used here in an effective manner to send request to the server to get online voting result but not again loading the whole page in server memory or rendering whole html content on to browser, instead calls a page that gives response or result in string and displays it onto a label in browser which looks like a windows desktop appliation.


So it works very simillar to javascript which behaves like working on client side.
It is trurly running in server but the response or test from server is used just to update a html control or display alert box etc...

Also things like suppose you are inserting bulk of records (2lakhs) into data base and it does not look good if the page gets hanged up unless all records are inserted.
Instead you can create a back end thread that inserts records into data base and using xml http reuest object you can call a web server page which runs sql statement that gives count of records and display the (count)status in page (number of records inserted still now) for every 2 mins .

Function that creates and returns the XmlHttpObject



function getAjaxObject()
{

var xmlHttpReq;
try
{
xmlHttpReq=new XMLHttpRequest();//for fire fox ,safari browsers
}
catch(e)
{
//For IE browsers. 2 for 2 different versions. i donot remember which of these are specific to
try
{
xmlHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
try
{
xmlHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
alert('Your browser doesnt support XmlHttpRequest');
return null;
}
}
return xmlHttpReq;
}
return xmlHttpReq;
}

The above mentioned java script function returns an "XMLHttpRequest" Object based on client browser.
By using this object we can interact with server page to run required logic and get response from it like calling a javascript function.

You can see there are 3 ways of creating xml http req object which depends upon the browser client uses. As this object plays vital role in sending http request to server and
retirve the response and embedded to html content using specific dom objects.



Example :


var xmlHttp=getAjaxObject();
if(xmlHttp!=null)
{
var url="../Test.aspx?L="+argu;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
alert(xmlHttp.responseText);
}
}
xmlHttp.send(null);

in a javascript function upon a button click


Form the above example
It is clear that we call this line of codes in javascript function since it should not reload the whole page,
First line retrieves the xml http object,
Next i am saving the url of the page which runs the logic accoriding to my requirement ans gives me response or text into a variable.(Along with query strings if there are)
Next xmlHttp.open("GET",url,true);

syntax :-

xmlHttp.open(type,url,asynchronously);


type can be "get" or "post"
usually when you have big or huge data to send to server (query string ) , we use "post"
when expecting result from server we use "get".

Url is the page address which gives appropriate response.

asynchronously defines that the state of sender after sending request and seeking for result.

If it is true (asynchronously) then as soon as the request is sent to the server , the browser does not stay or wait for response instead continues its execution to next line or function.

If it is false (synchronously) then browser stays or waits for the result from the server.

If we set it true (asynchronously) then it seems to be like a javascript function or logic running asynchronously that is Ajax (Asynchronous Java script).
It is also suggested to use true for effective response feel.



Next (Onreadystatechange) is an event that is calls a function every time the xml http request object state changes.



onreadystatechange is an event to handle response status.

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 requset is complete.

Next you can see an alert box that displays response text recieved from server.
That to in the state change event and the state value is 4 (complete)




There after we say "XMLHttpRequest" object send (null).
which means the request is sent to web server.
Note :
1) when you say send , if the request is asynchronous then your javascript continues to next line or function execution.
2) xmlHttp.status , helps in getting the status whether there is any error like server url not found etc...

Behind saying this process as Ajax i can also say it can be used as DHTML that is dynamically updating the html , of course the html content might be the response from server or
or logic build on client side according to the response text from web server.





Example using xml http object.

This application throws an alert box displaying the time at server (web server) and time at browser end upon a button click.

My aspx page

>%@ Page Language="C#" AutoEventWireup="true" CodeFile="XmlHttpResponse.aspx.cs" Inherits="XmlHttpResponse" %<

You can observer aspx page which gives response for XmlHttpRequest objects is blank except a page tag,
Page tag should be there so that server can identify this page based upon url sent through xml http request object.
(User Interface is not required, as this works as a back end service but does not load at client’s browser).


Code behind page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class XmlHttpResponse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Checking the reuest type and then giving desired response
if(Request.QueryString["ReqType"]!=null)
{
if (Request.QueryString["ReqType"].ToString() == "1")
{
//I considered request type 1 is to get the date and time at server side
string strServerTime = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
//Expires set to one says that after the response is sent to the requested browser no caching should be done.
Response.Expires = -1;
//Writing the response back to the requested browser
Response.Write(strServerTime);
}
}
}
}


Since there is no User interface for this aspx page which handles xml http request object and sends response, i can say this service (response for request) is similar to a web service.










Since in my case server and client are same machines, you can observe same time.
If it is the case with different machines you can different times and formats.







Cheers,
Srinivas

No comments: