How to use simple API using AJAX?


AJAX or Asynchronous JavaScript and XML is a set of existing technologies like: Asynchronous JavaScript and XML. AJAX helps us to fetch the data from any local database or any API without interfering with the existing page. It will fetch the data without reloading the page and without any interruptions.

Process of sending the AJAX request to any server.

  • Step 1 − In the first step, we will instantiate a XHR object using the XMLHttpRequest() as shown below −

const xhr = new XMLHttpRequest();
  • Step 2 − In the next step, we will open the xhr object created in last step using the open() method, which takes three arguments first is the type of request (GET, POST), second is the url of the server, third is a Boolean which represent the synchronous or asynchronous request (true means asynchronous, false means synchronous).

xhr.open('GET/POST', 'URL to the server, true/false);
  • Step 3 − In this step, we will check the state of the request and show the different messages on the screen according to the progress and the state of the request as shown below:

xhr.onreadystatechange = function(){
   if(document.readyState !== "complete"){
      result.innerText = "Loading Message";
   } else {
      result.innerText = "Data Fetched Successful Message";
   }
}
  • Step 4 − In the next step, we will get the response data in the JSON format by checking if the request is successful. Otherwise, it will show an error on the screen.

xhr.onload = function(){
   if(this.status === 200){
      const fetchedData = JSON.parse(this.responseText);
   } else {
      result.innerText = "Data Not Found, Some error occured!!!"
   }
}
  • Step 5 − In the final step of the process, we will send the request using the send() method. It is the most important step, because if the request is not sent to the server it will not be able to fetch the data. The request will be sent as shown in the below code:

xhr.send();

So far, we have discussed about the process of sending an AJAX request toa server. Now, we will implement the above process practically and understand it in details with the help of code example.

Steps

  • Step 1 − In the first step, we will define a button element which will help to fetch the data from the API once the user clicks on it. The button will send an AJAX request to the API on click to it.

  • Step 2 − In the next step, a table will be defined in which the data coming from the API will be shown on the screen and visible to the user.

  • Step 3 − In this step, we will write the JavaScript code to fetch the data from an API by sending an AJAX request using the process explained in the starting of the article.

  • Step 4 − In the next step, we will handle the data coming from the API in the form of JSON data. We will loop through each element of the final data array and get the object properties stored in it inside the columns of the table and fill each row with the relevant data.

  • Step 5 − In the final step, we will assign this whole functionality to the click event of the button as this all has to take place on click to the button.

Example

The below example will illustrate everything about sending a AJAX request to an API and handling the incoming JSON data to fulfil the needs −

<!DOCTYPE html>
<html>
<head>
   <!-- Bootstrap CSS CDN link included here -->
   <link href = "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel = "stylesheet">
</head>
<body>
   <div class = "container">
      <center>
         <h1>Use simple API using AJAX</h1>
         <p>The data of below table will be fetched using the AJAX request.</p>
         <p id = "result"> </p>
         <button id = "fetchBtn" class = "btn btn-primary"> Fetch Data </button>
         <table class = "table table-striped">
            <thead>
               <tr>
                  <th scope = "col"> Sr. No. </th>
                  <th scope = "col"> Name </th>
                  <th scope = "col"> Salary </th>
                  <th scope = "col"> Age </th>
               </tr>
            </thead>
            <tbody id = "table-body"></tbody>
         </table>            
      </center> 
   </div>
    
   <!-- Bootstrap script link is added here -->
   <script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
   <!-- Custom JavaScript to send the AJAX request and handle the data is written here -->
   <script>
      const result = document.getElementById('result');
      const fetchBtn = document.getElementById('fetchBtn');
      let finalData = [];
      const tableBody = document.getElementById('table-body');
      const fillTableData = (myData) => {
         // Filling the table with data
         myData.map((data) => {
            const tableRow = `<tr>
               <td> ${data.id} </td>
               <td> ${data.employee_name} </td>
               <td> Rs. ${data.employee_salary} pm </td>
               <td> ${data.employee_age} </td>
            </tr>`;
            tableBody.innerHTML +=  tableRow;
         })
      }
      const fetchDataHandler = () =>{
         // creating XHR object
         const xhr = new XMLHttpRequest();
         // opening XHR object to send asynchronous GET request to the api
         xhr.open('GET', 'https://dummy.restapiexample.com/api/v1/employees', true);
         // setting loading message during the progress
         xhr.onreadystatechange = function(){
            if(document.readyState !== "complete"){
               result.innerText = "Loading the data...";
            } else{
               result.innerText = "Data fetched successfully and filled in the table.";
            }
         }
         // getting data once it is available
         xhr.onload = function(){
            if(this.status === 200){
               const fetchedData = JSON.parse(this.responseText);
               finalData = fetchedData.data;
               fillTableData(finalData);
            } else {
               result.innerText = "Data Not Found, Some error occured!!!"
            }
         }
         // sending XHR request
         xhr.send();
      }
      fetchBtn.addEventListener('click', fetchDataHandler);
   </script>
</body>
</html>

In the above example, we have sent an AJAX request to a simple employee API and fetch the data stored there. The data we get after request completion will be raw and unstructured data. We used the JSON.parse() method to change data format into JSON format. After converting the data to JSON format, we get the required from the data bunch and loop through it to show it in the table format. The above functionality will take place once you click to the Fetch Data button to fetch and show the data on screen.

NOTE − If there is any error occurred after clicking the Fetch Data button, please try to Hard Refresh the browser and clear the cache memory. It will take 2 or 3 seconds to load the data from API.

Conclusion

In this article, we have discussed how we can use a simple API with AJAX. We have implemented it practically to understand it in details with help of code example and send the AJAX request to an API, fetch data from there and show it in a structured format such that in the form of a table on the main screen.

Updated on: 20-Nov-2023

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements