AJAX

Ajax is Asynchronous JavaScript and XML. In JavaScript AJAX is used to fetch data asynchronous from web server without refreshing webpage.

AJAX
JavaScript AJAX

AJAX benefits

  1. Load data from Web Server.
  2. Update a page content without reloading
  3. Load a text or media file from server or client.
  4. Send data to server in background.

Ajax History

Asynchronous loading techniques were first seen in Gmail and Google Maps websites in 2004-2005. Both of these web applications by google can change a portion of webpage without reloading entire page, thus enhance user experience.

In 2005, an article Ajax: A New Approach to Web Applications was published by Jesse James Garrett. On 5th Apr 2006, W3C standardised AJAX.

Asynchronous

Asynchronous means the request will not block other requests and run in parallel. The is the modern and most efficient way to send or receive data from server.

JavaScript

JavaScript, the clientside scripting language meant for frontend only can receive and send data from webserver without reloading webpage.

XML

XML or extensible markup language was used to send, receive and store data. Like HTML, XML use tags. But XML Tags custom made. In modern web apps, JSON is used instead of XML as JSON is lightweight and easy to parse.


XMLHttpRequest

XMLHttpRequest object is a build in constructor function of javascript. This object can send and receive data from web server. Older I.E. 7 and below use ActiveX Object. But all latest browsers use XMLHttpRequest as it is a web standard now.


    var xhr=new XMLHttpRequest();    
    

onreadystatechange

onreadystatechange is a javascript event for XMLHttpRequest constructor object. This event occurs when ready state of ajax changes. A callback function is called using onreadystatechange event. See example


    var xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function(){ };
    

readystate

readystate is a property of XMLHttpRequest object. readystate is an integer value between 0 to 4. This integer value tells the status of request.

0 : Unsent → open method not called yet

1 : Opened → Open method called but send method is not called yet

2 : Headers Received → send method called and http headers and status code received.

3 : Loading → Data is being receiving.

4 : Done → Data loading has been done.


Open method in ajax, open()

open method is used to open a request. There are three parameters in open method. First parameter is HTML Verb which can be get, post, put, patch and delete. Here are most commonly used HTTP Verbs with their uses.

HTTP Verbs

  1. GET → receive data from server
  2. POST → receive data from server with security.
  3. PUT → insert into server or to update.
  4. PATCH → to make partial request to server
  5. DELETE → to remove data from server

The second parameter of open method is URL Path or address

The third parameter of open method is boolean value. Default value is true. Here TRUE means request is send asynchronously and FALSE means request is send synchronously.


    xhr.open("get","data.php",true);

Send method in ajax, send()

Send method is used to send data using request. The parameters in send methods are data to be sent with request.

For get request, send method can be left blank as we are sending data only.

Send method using get


    xhr.open("get","data.php",true);
    xhr.send();

For post method, data can bed sent in key-value from or JSON String

Send method using post, key-value


    xhr.open("post","data.php",true);
    xhr.send("name=avinash");

Send method using post (JSON String)


    xhr.open("post","data.php",true);
    xhr.send("name:avinash");

HTTP Status

The HTTP Status property returns HTTP Status Code, which is an integer value. Here are some popular HTTP Status Codes.

  1. 200 → Response is successful
  2. 201 → Resource was created
  3. 204 → Request is successful, but no data received.
  4. 404 → Page Not Found

Receive data through ajax

In this example, we will learn how to fetch data from server using ajax. We are fetching data from php in this example.

View data.php file

document.querySelector("#btn").addEventListener("click",function(){
    var xhr=new XMLHttpRequest();
    xhr.open("get","data.php",true);
    xhr.send();
    
    xhr.onreadystatechange=function(){
    if(this.readyState==4 && this.status==200)
        console.log(this.responseText);
    }
    else if(this.readyState==3){
        console.log("data recieving")
    }
    else if(this.readyState==2){
        console.log("data processing")
    }
    else if(this.readyState==1){
        console.log("data sent")
    }
    else if(this.readyState==0){
        console.log("sending data ")
    }
    else{
    console.log("Unknown Error")
    }
})       

Receive JSON data through ajax

In this example, we will learn how to fetch data from .json file using ajax. We are fetching data from php in this example.

View avi.php file

document.querySelector("#btn").addEventListener("click",function(){
    var xhr=new XMLHttpRequest();
    xhr.open("get","avi.php",true);
    xhr.send();
    
    xhr.onreadystatechange=function(){
    if(this.readyState==4 && this.status==200)
        var t=this.responseText;
        var u=JSON.parse(t);
        for( var i in u ){
        console.log(i + ", "+ u);
        }
        
    }
    else if(this.readyState==3){
        console.log("data recieving")
    }
    else if(this.readyState==2){
        console.log("data processing")
    }
    else if(this.readyState==1){
        console.log("data sent")
    }
    else if(this.readyState==0){
        console.log("sending data ")
    }
    else{
    console.log("Unknown Error")
    }
})       

Ajax Loader

Ajax Loaders or Ajax spinners are GIF images used when data is loading or sending through ajax in javascript. This helps user understand that something is happening in background. In our next example, we will fetch data from an API, (GITHUB API) and see how AJAX Loader works.


document.querySelector("#btn2").onclick=function(){
    
    document.querySelector("#loader").removeAttribute("hidden");
    var ajax=new XMLHttpRequest();  
      
    ajax.open("get","https://api.github.com/users/robconery");
    ajax.send();
      
    ajax.onreadystatechange=function(){    
        if(this.readyState==0 || this.readyState==1 || this.readyState==2 || this.readyState==3){
        document.querySelector("#span2").innerHTML="Loading data";     
        }
        else if(this.readyState==4 && this.status==200){
        var t=this.responseText;
        var u=JSON.parse(t);
        for( var i in u){
        document.querySelector("#tab2").innerHTML+="<tr><td>"+i+"</td><td>"+u[i]+"</td></tr>";
         document.querySelector("#loader").setAttribute("hidden",true);   
        }    
        }
        else{
        document.querySelector("#span2").innerHTML="data could't fetch"; 
        document.querySelector("#loader").setAttribute("hidden",true);    
        }
        
    }
}