The jQuery Library provides us with all kinds of features and functionalities to get AJAX-related features on our web pages. That is, jQuery provides us with such functions, using which we can run any server-side script in our web page or request new data from the server without reloading our web page and send the incoming new data to our web.

Also, the functions that jQuery provides us related to AJAX, work in all web browsers due to being completely cross-browser compatible. Therefore, we do not need to write different JavaScript codes for different web browsers using different methods.

Today we will learn how to fetch data from API using ajax call and display it in an HTML table using jquery.

We will create a simple HTML page with a table that displays the data using jquery.

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://restapi.adequateshop.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,.

<script type="text/javascript">
    $(document).ready(function () {
        GetBindData()
    });
    //Get all employees
    function GetBindData() {
        $.ajax({
            url: 'http://restapi.adequateshop.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. 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://restapi.adequateshop.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.

 

The post [Best Way]-How to display JSON data in HTML using Ajax appeared first on Software Development | Programming Tutorials.



Read More Articles