AJAX is a very popular concept that is used to update the page without reloading the page. AJAX stands for Asynchronous Javascript And XML and because of that many Developers think that AJAX will only use XML to export and import data but that is not true. AJAX can use XML to transport any kind of data but can also transport data in JSON or any other plain text. In this article, we will see how to use JSON in transporting data using AJAX.
JavaScript Object Notation (JSON) is a format in which we store data and can use that data in transferring from one computer to another computer. It is very easy to understand and very light in weight. JSON is any simple text and can be converted to Javascript Objects and strings. It is language-independent, as many programming language support reading and generating JSON text.
Advantages of using JSON instead of XML in AJAX:
- The Code of JSON will be short in comparison to XML that’s why transferring data will be smooth
- JSON is easier to understand in comparison with XML
- In JSON we can easily represent a NULL Value.
AJAX works on Request and Response means AJAX will Request anything from the server and the server will give the Response back to AJAX. We have a built-in Object of Javascript known as “XMLHttpRequest” to send Responses and get Requests. There are some of the properties and methods of XMLHttpRequest, are described below:
- new XMLHttpRequest: It will create a new object by which we can send requests and receive responses.
- open(): It will specify any request. It takes various parameters like types of requests(GET or POST), location of server file, etc.
- send(): It is used to send a request to the server. It contains a string as a parameter if it is used for POST requests.
- onload: It is the property of XMLHttpRequest object which is used to define a function that will be called on complete loading of data.
- onreadystatechange: It is the property of XMLHttpRequest which is used to define a function that will be called on change of ready state. readystate is also a property of the XMLHttpRequest object.
- readystate: It is used to represent the status of the request. It can contain 5 values and every value has a different meaning.
- 0 means the request is not initialized
- 1 means Connection with the server is established
- 2 means the request is received
- 3 means processing the request
- 4 means the request is finished
- status: It is the property of XMLHttpRequest which is used to represent the status number of any request
- responseText: It is the property of XMLHttpRequest which is used to return the data of the response as a string
Steps for Sending the request with AJAX:
- Create a new XMLHttpRequest.
- Use the open() method of XMLHttpRequest to specify the request
- Use send() method of XMLHttpRequest to send request to the server
Steps for Getting a response from the server:
- Use the “onload” or “onreadystatechange” property of XMLHttpRequest to define a function that will help us to use our response at any place.
- You can use responseText inside that function to show your data anywhere on the webpage because responseText contains response data as a string.
- If you used “onload” property then you can use the responseText property directly inside the function. But if you will use “onreadystatechange” then you have to use the if condition to verify whether readystate became 4 or not because onreadystatechange will call the function every time when readystate changes but we need to use our responseText to show data when readystate becomes 4 because the response will be fully loaded only when the readystate becomes 4.
We will understand the above concept through the illustration.
Example 1: In this example, we will see how we can GET data from a server file using AJAX. Here, we took the server file in JSON format.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible"
content = "IE=edge" >
< meta name = "viewport"
content=" width = device -width,
initial-scale = 1 .0">
< title >JSON in AJAX</ title >
< style >
h1,
h3 {
text-align: center;
color: green;
}
button {
margin-left: 36.5rem;
}
#container {
text-align: center;
}
</ style >
< script >
function loadInformation() {
// Request
var request = new XMLHttpRequest();
request.open("GET", "./data.json");
request.send();
// Response
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Also checked status==200 to
// verify its status is OK or not
console.log(this.responseText);
document.getElementById("container")
.innerHTML = this.responseText;
}
}
}
</ script >
</ head >
< body >
< h1 >Geeks for Geeks</ h1 >
< h3 >JSON in AJAX</ h3 >
< button onClick = "loadInformation()" >
Click to Load
</ button >
< div id = "container" ></ div >
</ body >
</ html >
|
data.json:
{
"name":"Manish",
"age":"22",
"city":"Kolkata"
}
Output:

On Clicking the “click to load” button we have loaded data from a server file using AJAX without reloading the page
Javascript object will be converted into JSON format and then that data will be transported to the server side. On the server side that JSON data will be converted into Server side language.
JSON object has 2 methods, i.e., stringify() and parse() method which is used to convert the Javascript object into JSON string and back into a Javascript object.
- JSON.stringify(): It will convert the Javascript object into the JSON format string.
- JSON.parse(): It will convert the JSON string back into a javascript object
Example 2: In this example, we are using JSON.stringify() to convert the javascript objects into JSON format.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible"
content = "IE=edge" >
< meta name = "viewport"
content=" width = device -width,
initial-scale = 1 .0">
< title >JSON</ title >
</ head >
< body >
< script >
let gfg = {
name: "GeeksforGeeks",
Industry: "Software"
}
let ans = JSON.stringify(gfg);
console.log(ans);
</ script >
</ body >
</ html >
|
Output-
Example 3: In this example, we are using JSON.parse() to convert the JSON data that we obtained in the above example, into a javascript object.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible"
content = "IE=edge" >
< meta name = "viewport"
content=" width = device -width,
initial-scale = 1 .0">
< title >JSON</ title >
</ head >
< body >
< script >
let gfg = {
name: "GeeksforGeeks",
Industry: "Software"
}
let ans = JSON.stringify(gfg);
console.log(ans);
let ob = JSON.parse(ans);
console.log(ob);
</ script >
</ body >
</ html >
|
Output:

Similar Reads
ReactJS AJAX and API
APIs are used for fetching data from the server and using AJAX and API we call data asynchronously and show it in our HTML. You can make API requests by using browser built-in fetch function or third party libraries like Axios. Prerequisites:JavaScript and JSXKnowledge about react state and setState
4 min read
Difference Between JSON and AJAX
AJAXAjax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the server without refreshing the web page and thus increasing the user experience and better performance. There are two types of requests synchronous as well as asynchronous. Synchronous requests are the one
5 min read
How to do exception handling in Ajax ?
The purpose of this article is to demonstrate how we handle the exception in the jQuery AJAX request. A basic understanding of HTML, CSS, and jQuery is required. This can be done by an AJAX fail() method. We discuss 3 AJAX methods to better understand what's going on when making any ajax() request f
3 min read
What is polling in AJAX ?
In this article, we will see the polling with AJAX. Here, we are trying to create a polling-like experience using Javascript features like AJAX and Fetch API. Polling is the process of constantly and successively making HTTP calls until a required response is received. It is a very basic method to c
4 min read
Explain Storage Object in HTML
The HTML Storage Object is mainly used to locally store the data on the client-side web browser. It is a secure and easy way to store data of huge amounts on the web browser. It uses key-value pairs to store data on the web browser. The HTML Storage Object can store data on the web browser in two wa
3 min read
Explain HTTP Request in Backbone.js
Backbone.js is a compact library used to organize JavaScript code. An MVC/MV* framework is another term for it. If MVC is unfamiliar to you, it is just a technique for designing user interfaces. The creation of a program's user interface is made considerably easier by JavaScript functions. BackboneJ
4 min read
How to get JSON response in Ajax ?
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,
4 min read
Ajax Introduction
Introduction: The following tutorial will provide a short introduction to Ajax and its uses. Before understanding these terms see few practical examples to demonstrate the power of Ajax. Facebook, Instagram, Twitter etc are considered the situation when check news feed and if like someone post simpl
7 min read
JSON Hijacking
JSON(JavaScript Object Notation) denotes standard text-based-data format . It is widely used to provide a support mechanism between the server and the web application for the transmission of data. JSON Hijacking is a kind of network security attack. In this attack, an attacker targets a system that
10 min read
Explain the role of callback function in AJAX
AJAX (Asynchronous Javascript and XML) is used to create web applications asynchronous. It uses XMLHttpRequest to transport data to and from the server. AJAX always works on Request and Response means AJAX will Request anything from the server and the server will give the Response back to AJAX. We h
3 min read