How we can get JSON data using AJAX?

Asked 4 years ago Updated 7 days ago 1422 views

2 Answers


1

You can retrieve JSON data using AJAX by sending an HTTP request to a server and specifying that the expected response format is JSON.

Example using jQuery AJAX

<!DOCTYPE html>
<html>
<head>
    <title>Get JSON Data with AJAX</title>

    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<h2>User Details</h2>
<div id="result"></div>

<script>
$(document).ready(function () {

    // Send an AJAX GET request
    $.ajax({
        url: "data.json",          // URL of the JSON file or API
        type: "GET",               // HTTP request method
        dataType: "json",          // Expected response type

        // Executes if the request succeeds
        success: function (data) {

            // Display JSON data
            $("#result").html(
                "Name: " + data.name + "<br>" +
                "Age: " + data.age + "<br>" +
                "City: " + data.city
            );
        },

        // Executes if the request fails
        error: function (xhr, status, error) {
            $("#result").html("Error: " + error);
        }
    });

});
</script>

</body>
</html>

Sample data.json

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

Example using the native XMLHttpRequest

// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure the request
xhr.open("GET", "data.json", true);

// Handle the response
xhr.onload = function () {
    if (xhr.status === 200) {

        // Parse the JSON response
        var data = JSON.parse(xhr.responseText);

        // Display the data
        console.log(data.name);
        console.log(data.age);
        console.log(data.city);
    }
};

// Send the request
xhr.send();

Explanation

  • url: The endpoint or JSON file to retrieve data from.
  • type / method: Specifies the HTTP method (commonly GET or POST).
  • dataType: "json": In jQuery, tells AJAX to automatically parse the response as JSON.
  • success: Callback executed when the request completes successfully.
  • error: Callback executed if the request fails.

Modern Alternative (Fetch API)

Today, the recommended approach is to use the Fetch API instead of jQuery AJAX:

fetch("data.json")
    .then(response => response.json()) // Convert response to JSON
    .then(data => {
        console.log(data.name);
        console.log(data.age);
        console.log(data.city);
    })
    .catch(error => {
        console.error("Error:", error);
    });

The Fetch API is built into modern browsers, uses promises, and provides a cleaner, more readable syntax than traditional AJAX methods.

1

student.json

[

  {
    'ID': '1',
    'Name': 'Senpai',
    'Gender': '1',
    'Class': '32',
    'Seat': '15'
  },
  {
    'ID': '2',
    'Name': 'Yui Rio',
    'Gender': '0',
    'Class': '11',
    'Seat': '14'
  },
  {
    'ID': '3',
    'Name': 'Yuna Hina',
    'Gender': '0',
    'Class': '12',
    'Seat': '14'
  },
  {
    'ID': '4',
    'Name': 'Koharu Hinata',
    'Gender': '0',
    'Class': '21',
    'Seat': '14'
  },
  {
    'ID': '5',
    'Name': 'Mei Mio',
    'Gender': '0',
    'Class': '22',
    'Seat': '14'
  }
]

Example.html

<html>  

<head>
    <meta content='text/html; charset=utf-8'>
    <title>AJAX JSON by Javatpoint</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' crossorigin='anonymous'>
</head>
<body>
    <div class='container mt-3'>
        <h1 class='text-center'>fatch data from json file</h1>
        <button type='button' class='btn btn-primary' onclick='loadJSONData()'>Load JSON Information</button>
        <h2 class='mt-2 text-center text-danger' id='dummy'>Student table here</h2>
        <table id='loadDataInTable' class='mt-1 table table-striped table-hover'>
        </table>
        <p></p>
    </div>
<script >
    function loadJSONData() {
        var request;
        if (window.XMLHttpRequest) {
            request = new XMLHttpRequest();//for Chrome, mozilla etc
        }
        request.onreadystatechange = function () {
          if (request.readyState == 4) {
              var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
              let table = '<thead class=\'thead-dark\'><tr><th> # </th><th>Name</th><th>Gender</th><th>Class</th><th>Seat</th></tr></thead>';
              jsonObj.forEach(element => {
                  table += '<tr><td> ' + element.ID + ' </td>'
                      + '<td> ' + element.Name + ' </td>'
                      + '<td> ' + element.Gender + ' </td>'
                      + '<td> ' + element.Class + ' </td>'
                      + '<td> ' + element.Seat + ' </td></tr> ';
              });
              document.getElementById('dummy').remove();
              document.getElementById('loadDataInTable').innerHTML = table;
            }
        }
        request.open('GET', 'student.json', true);
        request.send();
    }
</script>
</body>
</html>  

Output

How we can get JSON data using AJAX?

How we can get JSON data using AJAX?

Write Your Answer