Learn About AJAX Basics

AJAX stands for Asynchronous JavaScript and XML.

AJAX is not a Programming Language. It helps us to update a part of web page without re-loading the entire webpage. It is used to exchange data with server in the background asynchronously.

Asynchronous means that the script will send a request to the server, and continue its execution without waiting for the reply. And when the response comes, it takes necessary action like updating the web page with data. This gives a the user a rich experience with web page.

AJAX is achieved with the help of object called ‘XMLHttpRequest’. This object is used to send and receive data from server. This object is built in Browser object.

Once the data is received from server, it is displayed to user with help of HTML DOM(Document Object Model) and Javascript.

HTML DOM can be used to access all elements of HTML and change their content.

Let us know more about how a request can be passed to server using XMLHttpRequest object.

Syntax for XMLHttpRequest object is

  1. variable = new XMLHttpRequest();  
  2. var objXHttp = new XMLHttpRequest(); //creates a new XMLHttpRequest  

Properties and methods of XMLHttpRequest

Let us look into few important properties and methods of XMLHttpRequest object:

Methods

Open(method, url, async, user, psw) specifies the request

The last two parameters User and password are optional

The first parameter methods will have either GET/POST depending on the scenario/requirement

Get is simpler and faster and used in most cases.

Post can be used when there is a large amount of data to sent to server/ for sending user input.

Post is more robust and secure and doesn’t have any size limitation when compared to GET.

  • Send() is used to send a request to server. This is used for GET requests.
  • Send(string) is used to send a request to server. This is used to POST requests.

Properties

onreadystatechange: This Property defines the method to be called when ready state of the XMLHttpRequest changes

readyState holds the status of XMLHttpRequest,

  1. request not initialized 
  2. server connection established
  3. request received 
  4. processing request 
  5. request finished and response is ready

So we can use this property to check if the response is ready or not.

The condition objXHttp.readyState == 4 if true implies that response is ready.

Status returns the status-number of request

A few values of status along with description are given below,

  • 200 implies ok
  • 403 implies “Forbidden”
  • 404 implies “Not Found”
  • Similarly, status==200 if true implies the status is ok for request.

responseText returns the response data as a string

Two Considerations which are important to be noted are,

  • The web page and the xml file to be loaded should be in same domain (same server). Modern browsers doesn’t allow us to access across domains.
  • Old versions of Internet Explorer (5/6) use an ActiveX object instead of the XMLHttpRequest object:

  1. variable = new ActiveXObject("Microsoft.XMLHTTP");  

To handle IE5 and IE6, check if the browser supports the XMLHttpRequest object, or else create an ActiveX object:

  1. if (window.XMLHttpRequest) {  
  2.     // code for modern browsers  
  3.     objXHttp = new XMLHttpRequest();  
  4. else {  
  5.     // code for old IE browsers  
  6.     objXHttp = new ActiveXObject("Microsoft.XMLHTTP");  
  7. }  

Let us look at a small example in which we make a request to server to update the web page asynchronously.

Example

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <body>  
  5.     <div id="demo">  
  6.         <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="loadDoc()">Change Content</button> </div>  
  7.     <script>  
  8.         function loadDoc() {  
  9.             var xhttp = new XMLHttpRequest();  
  10.             xhttp.onreadystatechange = function() {  
  11.                 if (this.readyState == 4 && this.status == 200) {  
  12.                     document.getElementById("demo").innerHTML = this.responseText;  
  13.                 }  
  14.             };  
  15.             xhttp.open("GET""ajax_info.txt"true);  
  16.             xhttp.send();  
  17.         }  
  18.     </script>  
  19. </body>  
  20.   
  21. </html> 

In this example, we are calling a function ‘loadDoc()’ on the button click of Change Content. In this function, we are creating a new request and telling server lo load the file ‘ajax_info.txt’ which is also in same domain asynchronously by specifying parameters of open method. Then we are changing div inner html with the response of the request in this case the contents of the file ‘ajax_info.txt’.

All this happens in the background, so that when button is clicked the text is changed without a whole page reload.

Thanks to AJAX for giving us a user friendly experience.

Next Recommended Reading AJAX Basics