Dynamic Column Header and Result from AJAX Call in jQuery DataTable

Introduction

jQuery DataTables provides an easy way to display data in an interactive and user-friendly table. In some applications, the table structure and column names may not be fixed and need to be generated dynamically based on data received from an AJAX request.

In this post we will explain how to create dynamic column headers and display results from an AJAX call using jQuery DataTables.

Prerequisites

Before implementing the example, make sure that:

  • jQuery is included in the application.
  • jQuery DataTables CSS and JavaScript files are included.
  • The AJAX response is available in JSON format.
  • The JSON response contains both column names and table data.

Implementation

Step 1: Include jQuery Plugin and CSS

<link rel="stylesheet" type="text/css"
href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

<script src="http://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>

<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

Step 2: Add the Following Script for DataTable Initialization with AJAX Call

$(document).ready(function($) {

    $.ajax({

        "url": "arrays.txt",

        success: function(json) {

            var tableHeaders = '';

            $.each(json.columns, function(i, val) {

                tableHeaders += "<th>" + val + "</th>";

            });

            console.log(tableHeaders);

            $("#tableDiv").empty();

            $("#tableDiv").append(
                '<table id="displayTable" class="display" cellspacing="0" width="100%">' +
                '<thead><tr>' + tableHeaders + '</tr></thead>' +
                '</table>'
            );

            $('#displayTable').dataTable(json);

        },

        "dataType": "json"

    });

});

Step 3: Inside Body Tag Write the Following Code

<div id="tableDiv"></div>

Step 4: Create a Text File

Create one text file named arrays.txt and add the following code:

{
    "columns": [
        ["Name"],
        ["Position"],
        ["Office"],
        ["Extn."],
        ["Start date"],
        ["Salary"]
    ],
    "data": [
        [
            "Tiger Nixon",
            "System Architect",
            "Edinburgh",
            "5421",
            "2011/04/25",
            "$320,800"
        ],
        [
            "Garrett Winters",
            "Accountant",
            "Tokyo",
            "8422",
            "2011/07/25",
            "$170,750"
        ],
        [
            "Ashton Cox",
            "Junior Technical Author",
            "San Francisco",
            "1562",
            "2009/01/12",
            "$86,000"
        ],
        [
            "Cedric Kelly",
            "Senior Javascript Developer",
            "Edinburgh",
            "6224",
            "2012/03/29",
            "$433,060"
        ],
        [
            "Airi Satou",
            "Accountant",
            "Tokyo",
            "5407",
            "2008/11/28",
            "$162,700"
        ],
        [
            "Brielle Williamson",
            "Integration Specialist",
            "New York",
            "4804",
            "2012/12/02",
            "$372,000"
        ],
        [
            "Herrod Chandler",
            "Sales Assistant",
            "San Francisco",
            "9608",
            "2012/08/06",
            "$137,500"
        ],
        [
            "Rhona Davidson",
            "Integration Specialist",
            "Tokyo",
            "6200",
            "2010/10/14",
            "$327,900"
        ],
        [
            "Colleen Hurst",
            "Javascript Developer",
            "San Francisco",
            "2360",
            "2009/09/15",
            "$205,500"
        ]
    ]
}

Step 5: Complete HTML Code

If you are following the above steps, you will get the following code:

<!DOCTYPE html>

<html>

<head>

<title>Data Table</title>

<!-- DataTables CSS -->

<link rel="stylesheet" type="text/css"
href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

<script src="http://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>

<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<script>

$(document).ready(function($) {

    $.ajax({

        "url": "arrays.txt",

        success: function(json) {

            var tableHeaders = '';

            $.each(json.columns, function(i, val) {

                tableHeaders += "<th>" + val + "</th>";

            });

            console.log(tableHeaders);

            $("#tableDiv").empty();

            $("#tableDiv").append(
                '<table id="displayTable" class="display" cellspacing="0" width="100%">' +
                '<thead><tr>' + tableHeaders + '</tr></thead>' +
                '</table>'
            );

            $('#displayTable').dataTable(json);

        },

        "dataType": "json"

    });

});

</script>

</head>

<body>

<div id="tableDiv"></div>

</body>

</html>

Conclusion

Using the above approach, the column headers and table results can be generated dynamically from the JSON response received through an AJAX call. This approach is useful when the table structure and data are not fixed and need to be loaded dynamically.

Frequently Asked Questions

1. Can jQuery DataTables support dynamic column headers?

Yes. Column headers can be generated dynamically from the JSON response before initializing the DataTable.

2. Can DataTables load table data using an AJAX call?

Yes. DataTables can work with data received through an AJAX request. In this example, the JSON data is loaded from the arrays.txt file.

3. What format should the AJAX response use?

The example uses JSON containing two main sections: columns for the column headers and data for the table results.

How to Get Selected Text and Value from a Drop-Down List Using jQuery

Talk to our experts

Looking for the right technology solution for your business? Our team of experts can help you with development, cloud, DevOps, design, and a wide range of other technology needs. Get in touch with our team here.

admin

Writes about Web & Architecture at Pheonix Solutions.

3 thoughts on “Dynamic Column Header and Result from AJAX Call in jQuery DataTable”

Leave a Reply

Scroll to Top