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:
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: "neveropen", 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: "neveropen", Industry: "Software" } let ans = JSON.stringify(gfg); console.log(ans); let ob = JSON.parse(ans); console.log(ob); </ script > </ body > </ html > |
Output: