Wednesday, September 2, 2009

AJAX: The Complete Tutorial Using Java Script

AJAX

Hai Guys, As I was sitting on bench in Organization I thought to write a Complete Article on AJAX , XMLHttpRequest Object and the web policies.


First of all let me introduce what is AJAX.

AJAX is the short for of Asynchronous JavaScript And XML In conventional web application the control of the sending request and handling response are in the hands of Browser. But in AJAX with use of JavaScript XMLHttpRequest Object it gives the complete handling of Sending Request and Handling the responses. Google was apparently the first to realize the power of XMLHttpRequest. With Gmail and Google Maps, they built applications that took advantage of this to provide a user.


AJAX comprises of different web development techniques as follows.

  1. XHTML, CSS for Data Presentations
  2. DOM(Document Object Model) for dynamic display of and interaction with data
  3. XML and XSLT for the interchange, and manipulation and display, of data, respectively
  4. XMLHttpRequest The Core JavaScript Object for asynchronous communication with Server
  5. JavaScript The Client Side Browser language to bring these technologies together

The above all technologies combinely help to create Interactive Rich Internet Applications.


What is XMLHttpRequest.

The XMLHttpRequest is the JavaScript object works as the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, as I mentioned above it was not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

In the AJAX the data can be returned as text or XML, here in text you can return the Complete HTML file as response if required.Before AJAX people used to Apply this by using IFrame by setting the URL.


XMLHttpRequest Life Cycle:

  1. create an XMLHttpRequest object (or equivalent Active X control in IE)
  2. Set the URL in XMLHttpRequest in which we want to connect;
  3. Set the callback handler javascript method to process response data;
  4. call the send() method, passing in any data to be posted;
  5. Program the callback handler method in such a way that it will process the response in meaningful way.


XMLHttpRequest Life Cycle in Detail:


1. Create the XMLHttpRequest object

It is the first and most straightforward step in AJAX implementation.As simple as any Object creation in any language in Javascript also we will define as follows.

var reqObj = new XMLHttpRequest();

This Object will work with almost all the web browsers other than Internet Explorer (But in later IE releases they started supporting for this..)),

To make the Object Standardized for all the web browsers we can define a method as follows.



 function createXMLHttpRequest() {
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) {
        alert("XMLHttpRequest not supported");
        return null;
    }
 }

[An Active X control is a type of embeddable Windows program component.]

function createRequestObj() {
       if (window.ActiveXObject) {
          xhr = new ActiveXObject("Microsoft.XMLHttp");
       } else {
          xhr = new XMLHttpRequest();
       }
    }


2. Setting Up the Request URL.

To make a call to the server, we first specify the URL that we want to connect to by the use of open() method in XMLHttpRequest, passing in the request URL.


xhReq.open("get", "studentDeatils.jsp", true);


XMLHttprequest Supports the following methods for making the Requests.


void open(DOMString method, DOMString url);

void open(DOMString method, DOMString url, boolean async);

void open(DOMString method, DOMString url, boolean async, DOMString? user);

void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);

void setRequestHeader(DOMString header, DOMString value);

void send();

void send (Document data);

void send ([AllowAny] DOMString? data);

void abort();


For Handling the response API supports the following methods.


readonly attribute unsigned short status;

readonly attribute DOMString statusText;

DOMString getResponseHeader(DOMString header);

DOMString getAllResponseHeaders();

readonly attribute DOMString responseText;

readonly attribute Document responseXML;


States of The XMLHttpRequest :

The readyState attribute, is the attribute provides current state of the XMLHttpRequest we made.


const unsigned short UNSENT = 0;

const unsigned short OPENED = 1;

const unsigned short HEADERS_RECEIVED = 2;

const unsigned short LOADING = 3;

const unsigned short DONE = 4;

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All HTTP headers have been received. Several response members of the object are now available.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)

The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

OPENED state has an associated send() flag that indicates whether the send() method has been invoked. It can be either true or false and has an initial value of false.

DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.


Note that we can POST data to the server (typically in XML format), or for simple cases, we could use GET and append some parameters to the URL. In the latter case, we'd just pass null to the send() method.

We used to pass in a local URL to the site from which the page is loaded. For security reasons:[The Cross URL XMLHttpRequest Will be discussed later. Viz Cross XHR], The Browsers Policies won't let you make an XMLHttpRequest to a URL from a different host to that from which the page was loaded.


3.Process data in the callback handler

As the Name says the call back method will not be executed at once, but rather asynchronously. Once the response came from the Server for every status of XMLHttpRequest.readyState this method will be invoked.

function responseProcessingFunction() {

// state of 4 means request completed

if (xhr.readyState == 4) {

var responseXML = xhr.responseXML;

// ... process the response ...

}

}


The resadyState = 4 means the request is DONE.


Limitation of Ajax

As the name suggests AJAX requires JavaScript Enabled Browsers.If the Browser doesn’t support or disabled the Application will not be running in web browsers. This alone means that AJAX applications will not work in web browsers and devices that do not support JavaScript. For this reason it is not accessible to many typical Web users
This is one of the limitations of the technology but as it’s having so many features the technology has many drawbacks too.

Future of Ajax:

AJAX is an extension of DHTML programming, adding the capability to dynamically send and retrieve data from the web server in response to user actions.The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities.
AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.Ajax has changed the face of the web forever. Save for some of the browser enhancements and a few other technologies, I dare to say that it’s had the most significant impact on the way we use the internet in its short life.


A Simple practical Example in JSP.


AjaxExample.html



<script language="JavaScript">
    function concatName()
    {
      // Create the XML request 
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      var URL="concat.jsp?firstName="+firstName+"&lastName="+lastName;
      xmlReq = null;
      if(window.XMLHttpRequest)
         xmlReq = new XMLHttpRequest();
      else if(window.ActiveXObject)               
      xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
      if(xmlReq==null){
         alert('Failed to Create Request.....')
         return; // Failed to create the request
      }

      // Anonymous function to handle changed request states
      xmlReq.onreadystatechange = function()
         {
             switch(xmlReq.readyState){
              case 0:              // Uninitialized
                      break;
              case 1: // Loading
                      break;
              case 2: // Loaded
                      break;
              case 3: // Interactive
                      break;
              case 4: // Done!
              // Alerting teh response as Text, and processing the responseXML(We are responding         as and XML from Server.)
                      processResponseText(xmlReq.responseText);
                      break;
              default:
                      break;
            }
         }
      // Make the request
      xmlReq.open ('GET', URL, true);
      xmlReq.send (null);
   }

   function processResponseText(responseText){
      var fullName=responseText;
      document.getElementById("concatName").value=fullName;
   }
</script>

AJAX Example

A Simple Concatenation Function Using AJAX First Name +<br/> Last Name -- <input type="button" value="Concatenate Name" onclick="concatName()"> -- ConcatenatedName= <input id="concatName"> </BODY> </HTML>
Concat.jsp
<%
    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");
    String fullName=firstName+" "+lastName;
    <%=fullName%>
    %>

AJAX Example This Page have simple the Concatenating Java Code.Just a replacement of Java Servlet to make the Example Simpler.

Reference:

http://www.javamex.com/tutorials/ajax/xmlhttprequest.shtml

http://www.w3.org/TR/2009/WD-XMLHttpRequest-20090820/

http://www.w3schools.com/Ajax/

And Obviously Google,