[Best Way]-How To Display JSON Data In HTML Using Ajax


The jQuery library offers a lot of features and functionalities, particularly in facilitating AJAX-related operations on web pages. With jQuery, we can execute server-side scripts, request new data from the server, and dynamically update our web pages without requiring a full reload.

One of the significant advantages of using jQuery for AJAX operations is its cross-browser compatibility. jQuery's AJAX functions work seamlessly across various web browsers, eliminating the need to write separate JavaScript code tailored for different browsers.

In this tutorial, we'll focus on fetching data from an API using an AJAX call and then displaying this data in an HTML table using jQuery.

We'll start by creating a simple HTML page containing a table, and then we'll use jQuery to fetch data from the API and populate the table with it.

We have to follow the following things:

  • First, we have to create an Html page and a table in it.
  • Add Reference of Bootstrap of CSS and Style
  • Write JavaScript Code for Getting Json using Ajax call.
  • Final Step Display json data from jQuery.ajax in HTML using loop

Step 1: Create Html page and table

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>How to display JSON data in HTML using ajax</h1>
        <br />
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>ZipCode</th>
                </tr>
            </thead>
            <tbody id="tblbody"></tbody>
        </table>
    </div>
</body>
</html>

Step 3: Display JSON data from URL using Ajax

For Our understanding purpose, let take an example, I have an API that returns the list of employees in the organization.

Now let’s say we want to bind that JSON response in the HTML table. Basically, we are going I want to Display JSON data in an HTML table using jQuery.

URL: http://samplerestapi.com/api/Metadata/GetEmployees

Json Response:

[
    {
    "$id": "1",
    "Id": 1,
    "Name": "Pascale Cartrain",
    "Address": "Rua do Mercado, 12",
    "City": "Walla",
    "ZipCode": "243232"
    },
    {
    "$id": "2",
    "Id": 2,
    "Name": "Liu Wong",
    "Address": "DaVinci",
    "City": "Paris",
    "ZipCode": "243232"
    },
    {
    "$id": "3",
    "Id": 3,
    "Name": "Miguel",
    "Address": "Avda. Azteca",
    "City": "London",
    "ZipCode": "243232"
    },
    {
    "$id": "4",
    "Id": 4,
    "Name": "Anabela",
    "Address": "ul. Filtrowa 68",
    "City": "New Delhi",
    "ZipCode": "243232"
    },
    {
    "$id": "5",
    "Id": 5,
    "Name": "Mary Saveley",
    "Address": "Adenauerallee",
    "City": "Tokyo",
    "ZipCode": "243232"
    }
]

Display JSON response from Ajax as HTML or table

Here I’m calling the ajax function and displaying the JSON data, to a table which easy to read by the user.On success  of  Ajax call function BindDataWithJqueyEach() javascript which loop through each object in JSON array,.

Below JavaScript/jQuery code is responsible for fetching data from an API endpoint and displaying it in an HTML table.

  • GetBindData Function: This function makes an AJAX call to the specified URL (http://samplerestapi.com/api/Metadata/GetEmployees) to fetch data from the server. It's configured to use the GET method to retrieve JSON-formatted data. Upon successful retrieval, it invokes the BindDataWithJqueyEach function to populate the table with the fetched data. In case of failure, it displays an alert with the error message.
  • BindDataToTable Function: responsible for populating the HTML table with the fetched data. It takes the data parameter, which represents the array of objects retrieved from the API. Inside the function, a loop iterates over each object in the data array. For each object, it constructs an HTML table row (<tr>) containing table data cells (<td>) for each property (Id, Name, Address, City, ZipCode). Finally, it appends the constructed table row to the <tbody> element with the ID tblbody, which is assumed to exist in the HTML markup.

Below script demonstrates how to use jQuery to fetch data asynchronously from an API endpoint and dynamically populate an HTML table with the retrieved data.


<script type="text/javascript">
    $(document).ready(function () {
        GetBindData()
    });
//Get all employees
    function GetBindData() {
        $.ajax({
            url: 'http://samplerestapi.com/api/Metadata/GetEmployees',
            method: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result)
            {
//after successfully call bind data to Table
                BindDataWithJqueyEach(result);
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
    }
    function BindDataToTable(data)
    {
if (data != null && data) {
for (var i = 0; i < data.length; i++) {
var tablerow = "<tr>"
                              + "<td>" + data[i].Id + "</td>"
                              + "<td>" + data[i].Name + "</td>"
                              + "<td>" + data[i].Address + "</td>"
                              + "<td>" + data[i].City + "</td>"
                              + "<td>" + data[i].ZipCode + "</td>"
                              + "</tr>";
                $("#tblbody").append(tablerow);
            }
        }
    }
</script>

Method-2 Using jQuery.each function bind data in the table

Using jQuery to build table rows from AJAX response

we are getting the data from server-side ajax response and we are trying to dynamically create table rows and add them to an existing HTML table. We can also use jQuery.each function if you don’t want to use the for loop. 

This JavaScript function, BindDataWithJqueyEach, iterates over each element in the provided data array using jQuery's jQuery.each() method. 

  • jQuery.each() Function: iterates over each element in the data array. For each element, the function defined within jQuery.each() is executed.
  • Function Parameters: The i parameter represents the index of the current element being processed, while val represents the value of the current element.
  • Constructing Table Rows: Within the function, a table row (<tr>) is constructed for each element in the data array. It includes table data cells (<td>) for each property of the current element (Id, Name, Address, City, ZipCode).
  • Appending Rows to Table Body: After constructing each table row, it is appended to the <tbody> element with the ID tblbody, assuming such an element exists in the HTML markup.

This function dynamically generates HTML table rows based on the data provided and appends them to the specified table body, effectively populating the table with the provided data.

See the below code.

function BindDataWithJqueyEach(data)
    {
        jQuery.each(data, function (i, val) {
var tablerow = "<tr>"
                             + "<td>" + val.Id + "</td>"
                             + "<td>" + val.Name + "</td>"
                             + "<td>" + val.Address + "</td>"
                             + "<td>" + val.City + "</td>"
                             + "<td>" + val.ZipCode + "</td>"
                             + "</tr>";
            $("#tblbody").append(tablerow);
        });
    }

Full Code

function GetBindemployeesData() {
            $.ajax({
                url: 'http://samplerestapi.com/api/Metadata/GetEmployees',
                method: 'GET',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
//after successfully call bind data to Table
if (result && result.length > 0)
                    {
                        jQuery.each(result, function (i, val) {
var tablerow = "<tr>"
                                + "<td>" + val.Id + "</td>"
                                + "<td>" + val.Name + "</td>"
                                + "<td>" + val.Address + "</td>"
                                + "<td>" + val.City + "</td>"
                                + "<td>" + val.ZipCode + "</td>"
                                + "</tr>";
                            $("#tblbody").append(tablerow);
                        });
                    }
                },
                fail: function (jqXHR, textStatus) {
                    alert("Request failed: " + textStatus);
                }
            })
        }

Output

how to fetch data from json file and display in html table using jquery

* if you have a question please comment

If you want understand Deferred Object properly so that when we use these Deferred Objects and their Methods for AJAX Functionalities, then we can get a better understanding of how to internally Deferred Objects by AJAX Functionality.Promises and Deferred Objects

Many times during programming, such a situation arises that after one function is fully executed, the function that generates the result, a second function call is made to use that result.

And the result that generates after this second function is fully executed, that result has to be used in a third function and this process can continue even further.

That is, the third function cannot be executed until the second function is executed and generates the result and the second function cannot be executed until the first function is executed and generates the result. To fulfill this type of need, we usually have to create a function by nesting it up to several levels.

Deferred Object offers a solution to this problem. Deferred Objects provide the facility to write such codes, which are not executed exactly at the same time and place at which they are written, but they are executed in the future when they match any other specific situation. Let us try to understand the Processing of Deferred Objects with an example.

Suppose you apply to get a job in XYZ company and you are called for an interview by the company. Now XYZ Company is the function in which you have to perform.

The interview you will give in this company will be a result of that interview and the result will be that either you will get a job in this company or you will not get the job.

For both these types of results, you create a plan because for both types of results you have to make some plan and you cannot decide these plans after the interview is performed.

That is, before giving an interview, you have to decide that if you get a job then what will you do and if you do not get a job in this company, then what will you do.

For example, if you got a job, then you have to see the arrangement of living in the city where you will reside, till you want to do a job in that company. Whereas if you do not get a job, then in that case you will need to book a ticket to come back to your home town. Or some other similar work may have to be planned.