How to get JSON response in Ajax ?
Last Updated :
16 Jan, 2022
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:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read