Load an Ajax DataTable on button click

How to load and display a DataTable with Ajax data on a button click. The Ajax data is from a GET request and once the table is loaded the button click will no longer fetch.

CodePen example.

Define the DataTable

Define the DataTable that will be getting loaded later, in this example below there also has been some options set.

let animal_table = $("#animals-table").DataTable({
    pageLength: 20,
    lengthMenu: [20, 30, 50, 75, 100],
    order: [],
    paging: true,
    searching: true,
    info: true,
    data: [],
    columns: [
        {data: "id"},
        {data: "guid"},
        {data: "name"},
        {data: "status"}
    ]
});

The most important parts are the id selector, the data being empty and the columns named.

The button click actions

Next for the button click action, the button being clicked will actually serve 2 purposes. The first being to unhide the table div and secondly to do an Ajax call and draw (fill) the table.

$(document).ready(function () {

    $("#load-dt").click(function () {
        if ($('.table-responsive').hasClass("hidden")) {
            $('.table-responsive').removeClass('hidden');
            $.ajax({
                url: "https://api.srv3r.com/table/",
                type: "GET"
            }).done(function (result) {
                animal_table.clear().draw();
                animal_table.rows.add(result).draw();
            })
        }
    });

});

Checking for the hidden class means that once the table has been unhidden and filled pressing the button won’t keep doing Ajax GET requests.

The DataTables API is used to first clear and then draw the table, using rows.add() adds new rows to the table using the data from the Ajax GET request.

The HTML

The basic HMTL using Bootstrap:

<div class="container">
    <div class="card">
        <div class="card-body">
            <div class="text-center">
                <button type="button" class="btn mb-1 btn-primary" id="load-dt">Click to load DataTable</button>
            </div>
            <div class="table-responsive hidden">
                <table id="animals-table" class="table table-striped table-bordered"
                       style="width: 100%">
                    <thead>
                    <tr>
                        <td>Id</td>
                        <td>GUID</td>
                        <td>Name</td>
                        <td>Status</td>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>