Open In App

How to get JSON response in Ajax ?

Last Updated : 16 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

AJAX is a set of technologies that allows users to fetch data asynchronously without interfering with the existing page. We can fetch various types of data using AJAX like JSON, XML, HTML, and text files.

In this article, we will see how to get JSON response in Ajax.

Approach: To solve this problem, we will first consider a JSON file named “capitals.json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals.html” which contains a table which we will use to populate the data we are getting in response. At last, we will create a JavaScript file named “capitals.js” to write code for fetching JSON data. In our code, We will be using plain JavaScript for achieving the given task. We are going to use the XMLHttpRequest object to make a request to a server and get its response.

Below is the step-by-step implementation of the above approach.

Step 1: Let’s see the JSON content that we are having.

capitals.json:

{
  "countries_capitals":[
  {
    "country":"India",
    "capital":"New Delhi"
  },
  {
    "country":"Italy",
    "capital":"Rome"
  },
  {
    "country":"Germany",
    "capital":"Berlin"
  },
  {
    "country": "Egypt",
    "capital":"Cairo"
  },
  {
    "country": "Australia",
    "capital":"Canberra"
  }
]
}

Step 2: HTML file which contains a table named “Countries and their capitals”, and a “Fetch” button to click so that on clicking it we will be able to populate the JSON data into the table.

Capitals.html




<!DOCTYPE html>
<html lang="en" dir="ltr">
  
<head>
    <meta charset="utf-8">
    <title>Countries and Capitals</title>
    <style>
        body {
            text-align: center;
        }
  
        h1 {
            color: #44A075;
        }
  
        table {
            border: 2px solid #44A075;
        }
  
        caption {
            margin: 10px 0;
        }
  
        tr {
            height: 30px;
        }
  
        th,
        td {
            border: 1px solid #44A075;
            width: 100px;
        }
  
        .info {
            display: flex;
            justify-content: center;
        }
  
        button {
            margin: 20px 0;
            height: 40px;
            width: 100px;
            cursor: pointer;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <div class="info">
        <table>
            <caption>Countries and their capitals</caption>
            <th>Countries</th>
            <th>Capitals</th>
            <tr>
                <td class="countries"></td>
                <td class="capitals"></td>
            </tr>
            <tr>
                <td class="countries"></td>
                <td class="capitals"></td>
            </tr>
            <tr>
                <td class="countries"></td>
                <td class="capitals"></td>
            </tr>
            <tr>
                <td class="countries"></td>
                <td class="capitals"></td>
            </tr>
            <tr>
                <td class="countries"></td>
                <td class="capitals"></td>
            </tr>
        </table>
    </div>
    <button id="fetchBtn" type="button" name="button">Fetch</button>
    <script src="capitals.js" charset="utf-8"></script>
</body>
  
</html>


Output:

Step 3: Here is our JavaScript file which contains the code to get JSON response using AJAX.

  • First, we will grab all the HTML elements that are our “Fetch” button and “Countries and their capitals” table columns so that we can populate it dynamically using DOM manipulation.
  • We will attach an Event Listener on our “Fetch”  button.
  • Then, we will create an XMLHttpRequest object.
  • After creating the XMLHttpRequest object, we will call its open method to open the request, the open method takes three parameters, an HTTP method(like GET, POST), URL of data that we want to fetch, and a boolean value(true means asynchronous request and false means synchronous request).
  • Then, use the getResponseHeader method which returns the string containing the text of the specified header, here will use this method to define which type of data we are fetching.
  • After this, we call the onload method which defines what to do after when the request completes successfully. Here in the onload method, we are first parsing the response text and iterating through all countries and capitals columns one by one using forEach loop and populating it with our parsed response text data.
  • At last, we will send a request to the server using the XMLHttpRequest object send method.

capitals.js




const fetchBtn = document.getElementById("fetchBtn");
const countries = document.getElementsByClassName("countries");
const capitals = document.getElementsByClassName("capitals");
  
fetchBtn.addEventListener("click", buttonHandler);
  
// Defining buttonHandler function
function buttonHandler() {
  
    // First create an XMLHttprequest object
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "capitals.json", true);
    xhr.getResponseHeader("Content-type", "application/json");
  
    xhr.onload = function() {
        const obj = JSON.parse(this.responseText);
        Array.from(countries).forEach((country, index) => {
            country.innerText = obj.countries_capitals[index].country;
        });
  
        Array.from(capitals).forEach((capital, index) => {
            capital.innerText = obj.countries_capitals[index].capital;
        });
    }
  
    xhr.send();
}


Now, if we will click the “Fetch” button, we will get to see our JSON data in the above table named “Countries and their capitals”.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads