AJAX with JSON

Rumman Ansari   Software Engineer   2023-03-26   178 Share
☰ Table of Contents

Table of Content:


AJAX with JSON

Some link contains JSON data. With the help of that we can play with them. For example in this link (https://jsonplaceholder.typicode.com/todos/1) you will get below sample data. You can fetch this data using AJAX. Let's see how you will be able to get that data in your project.


{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

HTML Code


<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <title>Hello, world!</title>
</head>

<body>
    <h1>Hello, world!</h1>
    <div id="demo">
        This is demo Div
    </div>
    <button type="button" onclick="loadDoc()">Change Content</button> 
    <script src="script.js"> </script>
</body>

</html>

SCRIPT Code

  • Here we used JSON.parse()
  • We got the element using document.getElementById("demo"), then appended data on that div.

headers('Content-Type: application/json;');
function loadDoc() {
    const xhttp = new XMLHttpRequest();

    xhttp.onload = function() {    
        myObj = JSON.parse(this.responseText); 
        let element = document.getElementById("demo");       
        element.append(" --- User Id - "+myObj.userId); 
        element.append(" --- completed - "+myObj.completed); 
        element.append(" --- Title - "+myObj.title);

    }

    xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1");
    xhttp.send();
  }

If you will run above code, you will get below output.