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
How to parse a JSON File in PHP?
We will explore how to parse a JSON file and display its data using PHP. PHP is a server-side scripting language commonly used to process and manipulate data. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for both humans and machines to read and write. It st
3 min read
How to get JSON data from request in Django?
Handling incoming JSON data in Django is a common task when building web applications. Whether you're developing an API or a web service, it's crucial to understand how to parse and use JSON data sent in requests. In this article, we will create a simple Django project to demonstrate how to retrieve
2 min read
How to Change Status of JsonResponse in Django
When developing APIs or AJAX-based web applications in Django, one of the most common tasks is returning JSON data as a response. Django provides the JsonResponse class to send JSON data easily. However, sometimes we might need to return a custom HTTP status code along with the JSON data.JsonRespons
5 min read
How to Handle Newlines in JSON?
Handling newlines in JSON is essential for maintaining data integrity when dealing with multiline text. JSON, being a text-based format, requires special consideration for newlines to ensure that text appears as intended across different platforms. Proper handling of newlines ensures consistent and
2 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data f
2 min read
How to read a JSON response from a link in Python?
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. T
2 min read
How to Encode Array in JSON PHP ?
Encoding arrays into JSON format is a common task in PHP, especially when building APIs or handling AJAX requests. Below are the approaches to encode arrays into JSON using PHP: Table of Content Using json_encode()Encoding Associative ArraysCustom JSON SerializationUsing json_encode()PHP provides a
2 min read
How to use JSON in Ajax jQuery ?
Using JSON in AJAX requests with jQuery is a fundamental aspect of web development. JSON or JavaScript Object Notation, offers a lightweight and structured format for data exchange between a server and a web application. jQuery simplifies this process further through its AJAX functionalities. We wil
3 min read
How to Receive and Analyze Response in Postman ?
If you're involved in API development or testing, you know how crucial it is to receive and analyze responses accurately. Postman, a popular API development tool, provides robust features for handling responses efficiently. In this article, we'll explore how to receive and analyze responses effectiv
7 min read
How to create and send GET requests in Postman?
Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, converting the API to code for various languages(like JavaScript, Pyt
1 min read