by BehindJava

How an AJAX Request works

Home » java » How an AJAX Request works

In this tutorial we are going to learn about AJAX Request working.

Before we starting to get into more depth of AJAX, it is necessary that we have a clear idea about XMLHttpRequest because it is the core of an AJAX Request. The XMLHttpRequest(Also known as XHR) is an API available in javascript. It used to send the HTTP request to a web server and load the server response back into the script. The XMLHttpRequest contains a callback handler function and it will invoke when the server response gets back to the script. Now we can move into an AJAX example, it will help for a better understanding about the XMLHttpRequest.

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  //callback function
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
  //Here also you can specify the content. 
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Change the content here</h2></div>
<button type="button" onclick="loadXMLDoc()">Call Ajax</button>

</body>
</html>

The above example shows a simple ajax request example. Here when you click on the Call Ajax button it will trigger the ajax event and loads the content in a text file (ajax_info.txt) into the browser.

On the starting of loadXMLDoc function the xmlhttp variable initialized as XMLHttpRequest in some browsers and it become initialized as ActiveXObject in some other browsers this is because in modern browsers we are using XMLHttpRequest as the ajax requesting object. But in old browsers like IE6, IE5 they are using ActiveXObject as the ajax requesting object.

After the initialization of xmlhttp variable it will send an ajax request to the server. The sending of an AJAX request is done by following lines of codes.

xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Here in the first line it will create a request and in the second line will send the request to the corresponding server. So in the first line the xmlhttp.open method will create an ajax request. This method contains three parameters which are.

  1. Type of request :- Which specifies the type of request(GET or POST)
  2. URL:- The location of the file on the server. Also, the URL become a server URL to.
  3. Async or sync parameter :- This boolean variable specifies the request type. If the variable is true then the request become Asynchronous and if the variable become false then the request become Synchronous.

Also the xmlhttp.onreadystatechange function act like a callback function it will invoke as Asynchronously or Synchronously depending upon the async/sync parameter boolean variable in xmlhttp.open method. When a response received from the server this function will become triggered. In our example what this function does is it will prints the content inside the ajax_info.txt file to the browser (between myDiv div tag).

The Request Life Cycle

From the above we found the working of an ajax with the example. Once again let us review the flow of Ajax event. Following steps explains the flow of an AJAX request

  1. From the browser, user triggers an Ajax event.
  2. An instance of XHR object is created. The call is created by the open() method and triggered by send() method.
  3. A request is made to the server, which will involve server-side processing.
  4. The server does the corresponding operation with the corresponding request.
  5. The response sends back to the browser. For the response, the default content type becomes text/XML.
  6. The callback function executes when the processed data return back to the client.

Methods and variables in XMLHttpRequest object

Let’s take a look at on the most advanced view of XMLHttpRequest object. In coding wise, the XMLHttpRequest object contains the following methods and variables.

void open(string method, string url, boolean asynch, string username, string password) :- This method setup the call to the server which represented in the URL. Available methods are GET, POST and PUT. The third parameter (synch) is used to hint whether the call is asynchronous or not. By default, it was asynchronous. The last parameters (username and password) is used to call requires user authentication.
void send(content) :- This method makes the request to the server. If the request was declared as asynchronous, this method returns immediately, otherwise it will wait until the response is received. void setRequestHeader(string header, string value):- This method is used to set the value for a given header value in the HTTP request. If this method is used it has to be called after open(). string getAllResponseHeader() :- This method will return a string containing response headers from the HTTP request. Headers include Content-Length, Date and URI. string getResponseHeader(string header) :- This method is similar with previous method but it return single header according to specified parameter.

In addition to the methods, XHR also has object properties as follows:

onreadystatechange :- The event handler that fires at every state change, typically a call to JavaScript function.
readyState :- The state of the request. It have mainly 5 possible values 0= uninitialized, 1=loading, 2=loaded, 3=intractive and 4 =complete.
responseXML :- The response from the server as XML. This object can be parsed and examined as a DOM object.
status :- The HTTP Status code from the server (200 for OK, 404 for Not Found …etc).
statusText :- the text version of the HTTP status code (like OK, Not Found …etc).