AJAX

AJAX stands for Asynchronous JavaScript and XML. In JavaScript AJAX is used to fetch data asynchronous from web server without refreshing webpage. For example, search results.

Ajax can send and receive data like XML, JSON, TEXT and HTML from web server without reloading.

JavaScript AJAX benefits

  1. Load data from Web Server.
  2. Update webpage content without reloading
  3. Communicate with web server asynchronously.
  4. Send data to server in background.
  5. Create Single Page Application
JavaScript AJAX
JavaScript AJAX

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 standardized 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 client side 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 are 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.


    const xhr=new XMLHttpRequest();    

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.


    const xhr=new XMLHttpRequest();
    xhr.open(method,url,async);

HTTP Verbs

  1. GET → receive data from server
  2. POST → Send data to server
  3. PUT → insert into server or to update.
  4. PATCH → to make partial modification
  5. DELETE → to delete specific resource

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.

using get in ajax request


    const xhr=new XMLHttpRequest();
    xhr.open("get","data.json");

using post in ajax request


    const xhr=new XMLHttpRequest();
    xhr.open("post","send.php");

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");
    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");
    xhr.send("name=avinash");

Send method using post (JSON String)


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

Ajax Events

Ajax request can be handled using onload or onreadystatechange events.

  1. onload
  2. onreadystatechange

onload

onload is used to fetch local files like .txt, ,html and .json. Load event triggered when XMLHttpRequest data is loaded completely. See example


    const xhr=new XMLHttpRequest();
    xhr.open("get","data.txt");
    xhr.send();
    xhr.addEventListener('load',function(){
        console.log(this.response);
    });

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


    const xhr=new XMLHttpRequest();
    xhr.open("get","https://api.domain.com");
    xhr.send()
    xhr.onreadystatechange=function(){
        // code goes here
     };

readystate

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

Value State Description
0 UNSENT Client created, open() not called
1 OPENED open() called
2 HEADERS_RECEIVED send() called, headers and status received
3 LOADING downloading response
4 DONE Data received

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. 403 → Forbidden
  5. 404 → Page Not Found
  6. 500 → Internal Server Error

Serve html file through ajax

In the first example, we will serve a static html file through ajax. To serve static files like html through ajax, make sure you are you are using localhost or live server.


    let xhr=new XMLHttpRequest();
    xhr.open('get','ajax.html');
    xhr.send();
    xhr.addEventListener("load",function(){
        console.log(this.responseText)
    });

Fetch JSON file through ajax

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


document.querySelector("#btn").addEventListener("click",function(){
    let xhr=new XMLHttpRequest();
    xhr.open("get","data.json");
    xhr.send();
    
    xhr.onreadystatechange=function(){
    if(this.readyState==4 && this.status==200)
        console.log(this.responseText);
    }
    else if(this.readyState==3){
        console.log("data receiving")
    }
    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")
    }
})       

Get php data through ajax

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


document.querySelector("#btn").addEventListener("click",function(){
    let xhr=new XMLHttpRequest();
    xhr.open("get","data.php",true);
    xhr.send();
    
    xhr.onreadystatechange=function(){
    if(this.readyState==4 && this.status==200)
        let t=this.responseText;
        t=JSON.parse(t);
        for( let i in u ){
        console.log(i + ", "+ u);
        } 
    }
    else if(this.readyState==3){
        console.log("data receiving")
    }
    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 or SVG 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.


<button>Get API Data</button>
<img class="loader" src="img/loader.gif" alt="" hidden>
<output class="errpr"></output>
<table id="tab2"></table>

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

Weather App using AJAX

In this example, we will learn how to buid weather app using javascript ajax.

Free weather APIs are available on internet. Use any api to fetch data.




    Weather Api by : https://openweathermap.org/