AJAX Tutorial

About AJAX

The AJAX is a short form of Asynchronous JavaScript and XML. It send the request asynchronous too the server so the user do not nee to wait till the response. The user can perform the different task meanwhile. Ajax is only a name given to a set of tools that previously existed. The main part is XMLHttpRequest, a class usable in JavaScript, which was implemented into Internet Explorer since the 4.0 version. The same concept was named XMLHTTP some times, before the Ajax name becomes commonly used. The use of XMLHttpRequest in 2005 by Google, in Gmail and Google Maps has contributed to the success of this format. But this is the name Ajax itself that made the technology so popular.

Why to use Ajax?

Mainly to build a fast, dynamic website, but also to save resources. For improving sharing of resources, it is better to use the power of all the client computers rather than just a unique server and network. Ajax allows performing processing on client computer (in JavaScript) with data taken from the server. The processing of web page formerly was only server-side, using web services or PHP scripts, before the whole page was sent within the network. But Ajax can selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all images, menus, etc... For example, fields of forms, choices of user, may be processed and the result displayed immediately into the same page.

Ajax in depth

Ajax is a set of technologies, supported by a web browser, including these elements:

  • HTML and CSS for presenting.
  • JavaScript (ECMAScript) for local processing, and DOM (Document Object Model) to access data inside the page or to access elements of XML file read on the server (with the getElementByTagName method for example)...
  • The XMLHttpRequest class read or send data on the server asynchronously.
  • optionally...

  • The DomParser class may be used
  • PHP or another scripting language may be used on the server.
  • XML and XSLT to process the data if returned in XML form.
  • SOAP may be used to dialog with the server.
  • The "Asynchronous" word, means that the response of the server while be processed when available, without to wait and to freeze the display of the page.

    Working of AJAX

    Ajax uses a programming model with display and events. These events are user actions, they call functions associated to elements of the web page.

    Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server.

    To get data on the server, XMLHttpRequest provides two methods:

  • open: create a connection.
  • send: send a request to the server.
  • Data furnished by the server will be found in the attributes of the XMLHttpRequest object:

  • responseXml for an XML file or
  • responseText for a plain text.
  • Take note that a new XMLHttpRequest object has to be created for each new file to load.

    We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyState attribute of XMLHttpRequest.

    States of readyState follow (only the last one is really useful):

  • 0: not initialized.
  • 1: connection established.
  • 2: request received.
  • 3: answer in process.
  • 4: finished.
  • The XMLHttpRequest class

    Allows to interact with the servers, thanks to its methods and attributes.

  • Attributes
    • readyState : the code successively changes value from 0 to 4 that means for "ready".
    • status : 200 is OK
      404 if the page is not found.
    • responseText : holds loaded data as a string of characters.
    • responseXml : holds an XML loaded file, DOM's method allows to extract data.
    • onreadystatechange : property that takes a function as value that is invoked when the readystatechange event is dispatched.
  • Methods
    • open(mode, url, boolean) :
      mode: type of request, GET or POST url: the location of the file, with a path. boolean: true (asynchronous) / false (synchronous). optionally, a login and a password may be added to arguments.
    • send("string") :
      null for a GET command.

  • Step by Step Guidence to build Application

    Step-1 : Getting Response object

    look into the given javascript function which uses the AvtiveX Control. This function will return the object of XMLHttpRequest to the calling funtion.

      function getAjaxRequest()
        var ajaxRequest;  // The variable that makes Ajax possible!
    		// Opera 8.0+, Firefox, Safari
    		ajaxRequest = new XMLHttpRequest();
    	} catch (e){
    		// Internet Explorer Browsers
    			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    		} catch (e) {
    				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e){
    				// Something went wrong
    				alert("Your browser broke!");
    				return false;

    The function uses try-catch the new XMLHttpRequest() will work for the Opera 8.0+, Firefox, Safari. If the browser is different other than the specified, the exception will be raised and in catch it will be again check for the internet Exprorer Browsers of Microsoft. Finally if something goes wrong the alert will be dipslayed to the user informing browser is not supprting the AJAX.

    Step-2 : Waiting for Server Response

      function setRequest()
         var ajaxRequest = getAjaxRequest(); // getting the request object
         ajaxRequest.onreadystatechange = function(){
    	 if(ajaxRequest.readyState == 1||ajaxRequest.readyState == 2||ajaxRequest.readyState == 3)
    	 else if(ajaxRequest.readyState == 4)
    		    alert("Error in getting response :"+ajaxRequest.status);
    		  document.body.style.cursor="default" ;
    	 ajaxRequest.open("GET", url , true); // Asynchronous call 
    	 ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    The function first get the HTTP requst object by calling the method as we disscuss above by calling
    var ajaxRequest = getAjaxRequest()

    ajaxRequest.onreadystatechange = function() will wait for the server response.

    document.body.style.cursor="wait" This statement will make the cursor in busy state so that user able know that the reponse from the server still not received by browser. readyState 0,1,2 and 3 correponding to "not initialized","connection established","request received","answer in process" as it disccussed above. When the readyState change the state to 4 it state that the reponse has been sent to client.

    if(ajaxRequest.status==200) If the reponse status code is 200 it state that reponse is successful. alert(ajaxRequest.responseText); will alert the response to the user. This can also process the XML reponse from the server. For that response will be taken ajaxRequest.responseXML. If the status code is other than 200 will transfer control to else loop which will alert user about the error code from the server.

    if(ajaxRequest.status==200) If the reponse status code is 200 it state that reponse is successful. if the status code is other than 200 will transfer control to else loop which will alert user about the error code from the server.

    Step-3 : Sending AJAX Request to server

    ajaxRequest.open("GET", url , true); will establish the connection with the server. Here the post method need to specify. The first argument of the function take the request method type POST/GET., the secode argument takes the URL to be post and the final argument is true/false. If it it true state that the request is Synchronous and browser will wait till the response come but if it is false its Asynchronous call to the server and browser can perform other task meanwhile the response come from the server.

    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); set the content type for the server.

    ajaxRequest.send(null); If the request method it GET then the this function will take "null argument" but if the method is post than user string and request paramenter name-values tring can be ponted to server by this method.

    The follwoing HTML shows the use of AJAX.

        <FORM method="GET" name="ajax" action="">                  
             <INPUT type="BUTTON" value="Submit"  ONCLICK="sendRequest()">
             <INPUT type="text" name="dyn"  value=""> 

    Include the above the javascript function in the head segment of the html file.