Implement AJAX in an application


I will start with a brief introduction of Ajax.

AJAX is an acronym for Asynchronous JavaScript And XML.


Using JavaScript technology, an HTML page can asynchronously make calls to the server from which it was loaded and fetch content that may be formatted as XML documents, HTML content, plain text, or JavaScript Object Notation (JSON). The JavaScript technology may then use the content to update or modify the Document Object Model (DOM) of the HTML page.


Web pages become more responsive using Ajax by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change. In simple words, we can say that Ajax is used to asynchronously get the information from the server and update only that area of the web page where this information fetched needs to be displayed, avoiding refresh of the entire page.

From the above diagram, we can summarize the steps to send an asynchronous call to the server.

1. Some client event occurs (Javascript call to the server)
2. An XMLHttpRequest object is created and configured.
3. An XMLHttpRequest makes a call.
4. The web server will exchange the data from the data stores.
5. Response is received from the web server and we can further handle the response accordingly.

Now, we will go with the details of this with the help of a simple application.

Step 1 : Create an HTML page with the following code

<html>
<head>
    <title>Ajax Implementation</title>
    <script src=”Request.js” type=”text/javascript”></script>
    <script src=”Response.js” type=”text/javascript”></script>
</head>
<body>
      <form id=”form1″ runat=”server”>
            <input type=”button” onclick=”GetName();” value=”Click” />
            <div id=”myDiv”></div>
      </form>
</body>
</html>

Step 2 : Create a Javascript file (save this file as request.js)

In this step, we have to create and configure the XMLHttpRequest object.

The XMLHttpRequest object is used to exchange data with a server behind the scenes. XMLHttpRequest object can be implemented in two ways, ActiveXObject is Internet Explorer specific, and XMLHttpRequest works with other browsers. So a check is made before creating the object, like this,

function GetXmlHttpObject()
{
    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;
            }
        }
    }
    return(xmlHttp);
}
Note :
       new ActiveXObject(“Microsoft.XMLHTTP”);
The ActiveXObject object is used to create instances of OLE Automation objects in Internet Explorer on Windows operating systems.
       variable = new ActiveXObject(“serverName.typeName”,location)
serverName — The name of the application that provides the object.
typeName — The type or class of the object to create.
location — The name of the network server where the object is to be created. This field is optional.



Now write another function to execute the XMLHttpRequest object

function executeXmlHTTPRequest()
{
      var xmlHttp = GetXmlHttpObject();
      xmlHTTP.onreadystatechange = function()
      {
            var id = 0;
            if(xmlHTTP.readyState == 4)
            {
                  if(xmlHTTP.status == 200)
                  {
                        Ajax_ServerResponse(xmlHTTP,id);
                  }
            }
      }
      xmlHTTP.open(“GET”,,true);
      xmlHTTP.send(null);
}
Note :
onreadystatechange event
When a request to a server is sent, we want to perform some actions based        on the response. The onreadystatechange event is triggered every time the
readyState changes. The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object: 
1) onreadystatechange — Stores a function (or the name of a function) to be       called automatically each time the readyState property changes
2) readyState — Holds the status of the XMLHttpRequest. Changes from 0 to 4. States are as follows :
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
3) status 200: “OK”
    404: Page not found                                                  
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object
open(method,url,async)
Specifies the type of request, the URL, and if the request should be handled
asynchronously or not.
     method: the type of request: GET or POST
     url: the location of the file on the server
     async: true (asynchronous) or false (synchronous)
send(string)
Sends the request off to the server.
     string: Only used for POST requests
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
1. A cached file is not an option (update a file or database on the server)
2. Sending a large amount of data to the server (POST has no size limitations)
3. Sending user input (which can contain unknown characters), POST is more
robust and secure than GET
Now finally, we make another function to call the above function.
function GetName()
{
    executeXmlHTTPRequest()
}
Step 3 : Create another Javascript file (save this file as response.js)
Now, we write a function to handle the response from the server. In executeXmlHTTPRequest() function above in request.js, when the status is 200,i.e. the request is being processed successfully, you can see that we have given a call to Ajax_ServerResponse(xmlHTTP, id) which is handled here.
function Ajax_ServerResponse(xmlHTTP, id)
{
   alert(“Server” + new Date());
   document.getElementById(“myDiv”).innerHTML = ‘Ajax Implemented Successfully  !!!’;
}
After executing the application, if you get the message “Ajax Implemented Successfully !!!“. Then your application have been successfully executed Ajax.
Try it out now !!!
Advertisements

3 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.