Ajax to auto populate table data periodically

 Let's consider below use case.

The train schedule is adjusted by the control room and exposed as a REST API to be displayed at each train station in near real time. So show the updated details to their passengers, these train station displays should call this REST API in a reasonable frequency and update the information. Below implementation shows how this can be achieved using Ajax technique. This can be used to any similar use case. The full sample code can be located at https://github.com/kladrock/ajax-sample-auto-refresh-table. To simulate the response from the train schedule REST API, we use this, https://raw.githubusercontent.com/kladrock/klad-rocks/main/trains.json.

First we need to call get the data from the REST API. It's done in the below code segment.

function loadData() {
    $("#example").DataTable();
    $.ajax({
        type: 'GET',
        url: testDataUrl,
        contentType: "text/plain",
        dataType: 'json',
        success: function (data) {
            let trainsData = data;
            populateScheduleTable(trainsData);
        },
        error: function (e) {
            console.log("There was an error executing the request!");
            console.log("error: " + JSON.stringify(e));
        }
    });
}

// populate the data table with train data
function populateScheduleTable(data) {
    console.log("Populating the schedule.");
    // clear old data.
    $("#example").DataTable().clear();

    Object.keys(data.trains).forEach(function(key) {
        $('#example').dataTable().fnAddData([
            key,
            data.trains[key].train_number,
            data.trains[key].departure,
            data.trains[key].destination,
            data.trains[key].arrival,
            data.trains[key].trip_time
        ]);
    })
}

In addition to calling the REST API and retrieving the data, this does an additional work in 'populateScheduleTable(data)' method. The retirved data from the REST API are populated to a Datatable that is defined in the index.jsp as in below code. Please note how the object model of the above code matches to this view.

<div class="panel">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Train Name</th>
<th>Train Number</th>
<th>Departure</th>
<th>Destination</th>
<th>Arrival</th>
<th>Trip Time</th>
</tr>
</thead>
</table>
</div>

Then there is the most important part which does the periodic updating of the table view with fresh data. This magic is done by below code segment.


$(document).ready(function () {
    loadData();
    setInterval(loadData, 5000); //refresh data every 5 seconds.
});

When I first came across the requirement, I couldn't locate any place where both these were put together. Hope this was useful to you.

Cheers!

Comments

Popular posts from this blog

Sign into Dokuwiki with Google

Single Sign On Integrations - Intro

Shibboleth based SSO for SAP