JSON AJAX Example

AJAX stands for Asynchronous JavaScript, and XML. Using AJAX, you can exchange data with the server and even update parts of a web page without reloading the entire page. In JavaScript, there are two functions that help you in dealing with JSON-

  • JSON.parse()- It converts JSON data received from a web server into JavaScript object.
  • JSON.stringify()- It converts JavaScript object into JSON data.

How to interact with JSON using AJAX

<html>
   <head>
      <title>JSON AJAX Example by Tutorialsandyou</title>
      <script type="application/javascript">
         function fetchData()
         {
            var request = new XMLHttpRequest();
	    request.onreadystatechange = function(){
	    if(this.readyState == 4){
	       var jsObj = JSON.parse(this.responseText);
	       document.getElementById("productTitle").innerHTML = jsObj.name;
	       document.getElementById("productDescription").innerHTML = jsObj.description;
	       document.getElementById("productPrice").innerHTML = jsObj.price;
	       document.getElementById("productSizes").innerHTML = jsObj.sizes[0]+" "+jsObj.sizes[1];
            }
         };
         request.open("GET", "/json/product.json", true);
         request.send();
	}
      </script>
   </head>
   <body>
      <button onclick="fetchData()">Click Here</button><br />
      Title: <h1 id="productTitle"></h1>
      Description: <p id="productDescription"></p>
      Price: <p id="productPrice"></p>
      Sizes: <p id="productSizes"></p>
   </body>
</html>	

Output


Title:

Description:

Price:

Sizes: