Wednesday, July 20, 2016

Ajax - Tutorial Part I - Your First program

Ajax -Introduction

Ajax (Asynchronous JavaScript and XML )is not a programming language, Its a script. It will update parts (div) of the web page, without reloading the whole page. For example, selecting drop down values.

So it will make web page as Fast and Dynamic and It supports asynchronous operation.

Synchronous: We can send single request at a time and need to wait to get the response before sending second request.

Asynchronous: It will support to send second request before receiving the response of first request. Ajax will support asynchronous. So that its good for web applications.

You must know, JavaScript, CSS and little bit knowledge of xml to work with Ajax.


How to create XMLHttpRequest Object ?

Almost all modern browsers have built-in with XmlHttpRequest object. But older version like IE5 and IE6 will not support this. So in this case you should use ActiveX object.

Let see the syntax ,


variable = new XMLHttpRequest(); // Latest Browsers


variable = new ActiveXObject("Microsoft.XMLHTTP"); // Old Browsers

Methods of XmlHttpRequest

Method Description
abort Abort was introduced in Internet Explorer 7. The abort method interrupts an asynchronous operation in progress.

getAllResponseHeaders Returns all the response headers, separated by CRLF, as a string, or null if no response has been received.

getResponseHeader Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.

open Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.

overrideMimeType Overrides the MIME type returned by the server.

send Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent..

setRequestHeader Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().


Apart from these, some non standra method also there. Please refer Here .


Properties of XMLHTTPrequests


Below are the properties of XmlHttpRequest.

1. onreadystatechange - This property sets the method to be called on every state change. This is usually your event handler for the asynchronous callback.

2. ReadyState - It will defines the state of the XmlHttpRequest.Possible values include:


        0 Uninitiated
        1 Loading
        2 Loaded
        3 Interactive
        4 Complete

When sending XmlHttpRequest, check to see if the readyState is 0 or 4, and while asynchronous callback handler, will check to see if readyState is 4.

3. responseText - Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.

4. responseXML - Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML.

5. Status - Returns an unsigned short with the status of the response of the request.

6. statusText - Returns a DOMString containing the response string returned by the HTTP server. Unlike XMLHTTPRequest.status, this includes the entire text of the response message ("200 OK", for example).

Apart from these, lot of properties available , Please refer Here.

Ajax simple program

Below are simple ajax program, let see the code and explanation. Just create one html file and text file and keep the same in under same directory.

<html>
<head>
<script type="text/javascript">
function ajaxFirst()
{
var a;
 
    if (window.XMLHttpRequest)
    {// If the browser if IE7 or Firefox or Chrome or Opera or Safari (Modern Browsers)
      a=new XMLHttpRequest();
    }
   else
    {//If browser is IE6, IE5 (Old Browsers)
      a=new ActiveXObject("Microsoft.XMLHTTP");
    }
 
a.onreadystatechange=function()
{
  if (a.readyState==4 && a.status==200)
  {
    document.getElementById("myDiv").innerHTML=a.responseText;
   }
}
 
a.open("POST","sample.txt",true);
a.send();
} // ajaxFirst() close
</script>
</head>
<body>
 
<div id="myDiv" style="width: 300px; height: 30px;">Please click on below button</div>
<button type="button" onclick="ajaxFirst()">Change Content Here</button>
 
</body>
</html>
Code Explanation :

1. When the button is clicked , onClick event will call ajaxFirst() javascript method.
2. If your browser is modern like latest, then it will create XmlHttpRequest, else ActiveXObject will be created.
3. Next it will open a connection and send the request your sample text file. True parameter mentioned here, you are enabling Asynchronous operation.
4. Then send method will send the request.
5. After receiving response from server, it will execute onreadystatechange automatically.
6. Readystate 4 mentioning , it is completed and 200 status code mentioning response is success.

No comments:

Post a Comment