Ravi Tutorials Provide Project Training

AJAX

AJAX Introduction





AJAX stands for Asynchronous JavaScript and XML . AJAX is a dream of every developers because it is used to :
  • Update any web page without reloading/refreshing the page
  • Request data to a server - after the page has loaded
  • Receive data from a server - after the page has loaded
  • Send data to a server in the background without reloading





Simple Example of AJAX

<!DOCTYPE html>
<html>
<body>

     <div id="AjaxDemo">
            <h2>Let's Try  AJAX to change text</h2>
            <button type="button" onclick="ChangeText()">Change Data</button>
     </div>

</body>
</html> 

The HTML page contains a div section having id "AjaxDemo" and a Button. The div section is used to display information received from a server. The Button calls a function "ChangeText()" when it is clicked. The function requests data from a web server and displays it in div id "AjaxDemo"

function ChangeText() 
{
  var xhttp = new XMLHttpRequest();
 
 xhttp.onreadystatechange = function() 
  {
  
  if (this.readyState == 4 && this.status == 200)
    {
        document.getElementById("AjaxDemo").innerHTML = this.responseText;
    }

  };
   
  xhttp.open("GET", "AjaxTest.php", true);
  xhttp.send();
}





What is AJAX and How it Works ?

AJAX = Asynchronous JavaScript And XML. AJAX is not a programming language. AJAX just uses a combination of
  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text. AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Working of AJAX

  • An event occurs in a web page (the page is loaded, a button is clicked)
  • An XMLHttpRequest object is created by JavaScript
  • The XMLHttpRequest object sends a request to a web server
  • The server processes the request
  • The server sends a response back to the web page
  • The response is read by JavaScript
  • Proper action (like page update) is performed by JavaScript

XMLHttpRequest Object





XMLHttpRequest object is the Backbone of AJAX















The XMLHttpRequest Object

XMLHttpRequest object is supported by all modern browsers. This object is used to send & receive data to server & from server in background. It means user can change or update information on web-page without refreshing or reloading the complete page.

How to Create XMLHttpRequest Object

New versions of all browsers like IE, FireFox, Chrome etc have pre defined XMLHttpRequest object. Below is the syntax to create XMLHttpRequest object :
VariableName = new XMLHttpRequest();
But on the other hand Old versions of IE cannot support XMLHttpRequest object. They use an ActiveX Object. Below is the syntax of ActiveX object :
variable = new ActiveXObject("Microsoft.XMLHTTP");
So to execute program of AJAX on browser, It is very important for user or developer to check compatibility of either XMLHttpRequest or ActiveX object
var xhttp;

if (window.XMLHttpRequest) 
{
    xhttp = new XMLHttpRequest();
} 

else 
{
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Where to Upload Web Page & Other Related Files

It is very important to know that where we have to upload all the files related with web page and ajax. Updated browsers do not support to allow accessing files from other domains due to security reason. This means that both the web page and all related files must be on the same domain and on the same server. The examples on W3Professors, all files and XML files located on same domain. If anyone tries to use the examples then he/she has to upload all related filed on their own and same server.

How to Handle Old Versions of Browser

If you have old version of any browse like IE (IE5 and IE6), then XMLHttpRequest object will work properly on it. So to deal with these versions, developers has to use ActiveX Object in place of XMLHttpRequest object
if (window.XMLHttpRequest) 

{
    // Below line for updated browsers
    xmlhttp = new XMLHttpRequest();
 } 

else 

{
    // below line for old versions browsers. Like IE
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

XMLHttpRequest Object Methods

MethodDescription
new XMLHttpRequest()Creates a new XMLHttpRequest object
abort()Cancels the current request
getAllResponseHeaders()Returns header information
getResponseHeader()Returns specific header information
open(method,url,async,user,psw)Specifies the request

method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send()Sends the request to the server
Used for GET requests
send(string)Sends the request to the server.
Used for POST requests
setRequestHeader()Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

PropertyDescription
onreadystatechangeDefines a function to be called when the readyState property changes
readyStateHolds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseTextReturns the response data as a string
responseXMLReturns the response data as XML data
statusReturns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to theHttp Messages Reference
statusTextReturns the status-text (e.g. "OK" or "Not Found")

Send Request To Server





The XMLHttpRequest object is used to exchange data with a server.















How XMLHttpRequest Send a Request To a Server

open() method and send() method are two important methods of Object XMLHttpRequest are used to send/receive data with server.
xhttp.open("GET", "AjaxTest.php", true);
xhttp.send();
Method NameDescription
open(method, url, async)Specifies the type of request

method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send()Sends the request to the server (used for GET)
send(string)Sends the request to the server (used for POST)


















Difference Between GET & POST?

GET is simpler and faster than POST, and can be used in most cases. However, always use POST requests when :
  • A cached file is not an option (update a file or database on the server).
  • Sending a large amount of data to the server (POST has no size limitations).
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET.

Examples of GET Requests


A simple GET request
xhttp.open("GET", "GetDemo.php", true);
xhttp.send();
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
If you want to send information with the GET method, add the information to the URL:
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();