Explain JSON in AJAX?


JSON, or JavaScript Object Notation, is a simple format for exchanging data. It is a human−readable and machine−understandable format. It is based on a portion of Standard ECMA−262, Third Edition, December 1999's JavaScript Programming Language. Despite using conventions recognizable to programmers of the C family of languages (C, C++, Java, JavaScript, Perl, Python, and many others), JSON is a text format fully independent of the programming language. JSON is the best language for exchanging data due to its characteristics and simplicity.

AJAX is a method of web development used to build interactive web applications. Web pages can request data from servers using AJAX without reloading the page. The JSON format is one that the AJAX technique uses to represent data. We can easily convert any information or data into JSON format, which is very easy to understand.

JSON Object

In the modern world, most developers use JSON over XML to exchange the server's data. JSON has some benefits over XML when it comes to AJAX. Compared to XML, JSON's code is shorter, which makes data transfer easier. JSON is also simpler to understand by both machines and humans. Finally, JSON makes it simple to represent a string, number, Boolean, array, or Null value.

The JavaScript object can easily be converted into JSON and sent to the server. The JSON data will then be pursued on the server side. The JavaScript object is transformed into a JSON string and back into a JavaScript object using the JSON object's stringify() and parse() methods.

  • JSON.stringify() − This function turns a JavaScript object into a string in JSON format.

  • JSON.parse() − The JSON string can be transformed into a JavaScript object.

Properties and Methods of XMLHttpRequest

AJAX uses the Request and Response model, which implies that it can ask the server for anything and receive the response in return. We have a built−in Javascript object called "XMLHttpRequest" that we can use to send responses and receive requests. The following is a description of some of the XMLHttpRequest's attributes and methods−

  • new XMLHttpRequest − This creates a new object we can use to submit requests and get responses.

  • open() − This function allows for any request. It requires several arguments, including request types (GET or POST), server file location, etc.

  • onload − The XMLHttpRequest object's onload field specifies a function invoked when data loading is complete.

  • send() − The send() function sends a request to the server. If it is used for POST requests, it has a string as an argument.

  • status − The XMLHttpRequest property used to express the status number of any request is status.

  • onreadystatechange − This XMLHttpRequest attribute allows you to specify a function that will be called when the ready state changes. The XMLHttpRequest object also has a property called readystate.

  • responseText − This XMLHttpRequest attribute returns the response's data as a string.

  • readystate − This identifies the request's current status. It has a maximum of 5 possible values, each with a unique meaning. 0 denotes that the request has not been initiated. 1 indicates a successful connection to the server. 2 denotes receipt of the request. 3 represents the request's processing. 4 means the completion of the request.

Sending the request with AJAX

Below are the steps for sending the request with AJAX

  • Develop a new XMLHttpRequest objects

  • Specify the URL you want to request

  • Call the open() method, passing in the HTTP method and URL as parameters

  • Add an event listener for the onreadystatechange event

  • Call the send() method, passing in any data to be sent with the request

  • Handle the response

Example 1- Get JSON object by AJAX

In this example, we use AJAX to perform an HTTP request and get the response in the form of JSON. We use the XMLHttpRequest object and the open and onload methods to perform AJAX calls. We used a button click event to perform the AJAX call and show the response on the webpage.

<html>
<body>
   <h2> JSON and AJAX </h2>
   <button onclick = "getJSON()">
   Click on the button to get JSON data by AJAX call
   </button>
   <div id = "root" style = "border: 1px solid black; padding: 1%"> </div>
   <script>
      function getJSON() {
         //AJAX Call
         let http = new XMLHttpRequest()
         http.open('GET', 'https://jsonplaceholder.typicode.com/posts/1')
         http.onload = function () {
            document.getElementById('root').innerHTML =
            'JSON response: <br /><br />' + this.response
         }
         http.send()
      }
   </script>
</body>
</html>

Example 2: Send JSON object by AJAX

In this example, we use AJAX to perform an HTTP request and send JSON data to the server. We use the POST method in the AJAX call to send data to the server. We use the XMLHttpRequest object and the open and onload method. We used a button click event to perform the AJAX call and show a message if the JSON data is successfully sent to the server.

<html>
<body>
   <h2> JSON and AJAX </h2>
   <p id = "mypara" style = "border: 1px solid black"> JSON object: </p>
   <button onclick = "postJSON()">
   Click on the button to send JSON data by AJAX call
   </button>
   <div id = "root" style = "border: 1px solid black; padding: 1%"></div>
   <script>
      let JSON_OBJECT =
      '{"name": "ABC", "class": 10, "roll": 12, "subject": "Computer"}'
      //Showing JSON_OBJECT in the webpage
      document.getElementById('mypara').innerHTML += '<br />' + JSON_OBJECT
      function postJSON() {
         //AJAX Call
         let http = new XMLHttpRequest()
         http.open('POST', 'https://jsonplaceholder.typicode.com/posts/')
         http.onload = function () {
            document.getElementById('root').innerHTML =
            'JSON data send successfully!'
         }
         http.send(JSON_OBJECT)
      }
   </script>
</body>
</html>

In this tutorial, we learn about JSON in AJAX. We learned about JSON Object, Properties and methods of XMLHttpRequest and Sending the request with AJAX.

Updated on: 29-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements