Create Interactive HTML Tables Populated With API Data

Michael Markin
Level Up Coding
Published in
5 min readDec 6, 2021

--

Image by Quaid Lagan on Unsplash

Overview

A website I recently built required a dynamic table populated with live data from API calls. Simple HTML was not going to cut it.

So I turned to jQuery DataTables, a free library that makes it easy to add user-friendly features to any HTML table.

My table displayed forecasts loaded from a weather API (and driving distances from a navigation API) for dozens of New Jersey’s popular beaches. This was the final result.

GIF by the author. Check out the full project on GitHub

However, getting to this point was quite a headache — especially with the sparse amount of documentation available for those using JavaScript on the server-side.

In this article, I will cover the fundamental structure needed to connect an HTML table’s data feed to a JS server-side script.

Plan

Let’s get started by following a sample project.

Oftentimes, our data will not be hard-coded. It will most likely be retrieved from an API. Our goal will be to populate the table’s contents with fake data from this online REST API (which is free and does not require an API key).

Image by the author. Sample data from here

Project Folder

It is important to maintain a proper file structure within your root project folder.

Here is what mine looks like:

Image by the author

For testing, I will be launching the web server locally using Node.js. The sample project files and required packages can be found on GitHub here.

Table HTML

First, we need to include the necessary source files. Copy and paste this code block high up in your HTML file. It will import the JQuery library, DataTables Javascript, as well as CSS files that I personally prefer to have over the default styling of the table.

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.1/css/dataTables.bootstrap5.min.css"><script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script><script type="text/javascript" language="javascript" 
src="https://cdn.datatables.net/1.11.1/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.11.1/js/dataTables.bootstrap5.min.js"></script>

Then, create the HTML table and give it appropriate column names.

For DataTables to be able to enhance an HTML table, the table must be valid, well formatted HTML, with a header (thead) and a single body (tbody). An optional footer (tfoot) can also be used.
- DataTables Documentation

<div class="container" style="width:60%;">
<table id="example">
<thead>
<tr>
<th scope="col">USER ID</th>
<th scope="col">ID</th>
<th scope="col">TITLE</th>
<th scope="col">COMPLETED</th>
</tr>
</thead>
</table>
</div>

Initializing DataTables

Now, let’s initialize DataTables within the HTML file. In this code block, we tell DataTables to select our HTML table with id=“example” and load data once the document is fully ready.

<script type="text/javascript" class="init">$(document).ready(function() {
// Create a new DataTable object
table = $('#example').DataTable({
ajax: {
url: '/exampleData',
},
columns: [
{ data: 'userId' },
{ data: 'id' },
{ data: 'title' },
{ data: 'completed' }
]
})
});
</script>

The ajax.URL() method is applied to define the Ajax data source for the table. In this case, DataTables will seek to fetch data from /exampleData; we will implement an app.get() request function to handle this in the next step.

Essentially, DataTables is sending a GET request via Ajax to the server-side while expecting JSON data in return.

There are many ways to handle and manipulate the JSON response before loading the table. Refer to this page of the documentation.

In our case, the JSON response is an array of fake todo items, in which each item is a row of the table. The columns parameter is there to provide additional detail on where each data point of an item goes on the table. For example, the first item within the response array is:

[ {
“userId”: 1,
“id”: 1,
“title”: “delectus aut autem”,
“completed”: false
},

]

So { data: ‘userId’ } specifies that the 1st column of our table will receive the data paired to the “userId” key. If you have nested data, the columns method will help you access it by using dotted object notation.

Server-side API Request

On the server-side, we can define a route handler for HTTP GET requests using the Express package.

app.get("/exampleData", function (req, res) {const url = 'https://jsonplaceholder.typicode.com/todos';// Make a request
axios.get(url)
.then(response => {
// send the collected data back to the client-side DataTable
res.json({
"data": response.data
})
})
.catch(function (error) {
// handle error
res.json({"error": error});
})
});

So now, every time DataTables sends a GET request to the url exampleData, it will be received here. Once that happens, we retrieve data from the API and then send it to DataTables on the client-side. The data sent to DataTables is in the form of a JSON payload which, subsequently, populates the table.

The data parameter is required in the response and denotes the data to be used by DataTables. When triggered, the error parameter can be applied to display an error message on the user’s page.

At this point, the table populates with data each time the page loads or is refreshed.

Image by the author. Snapshot from localhost:3000

Customization Options

After initializing DataTables, the library automatically added responsive searching, ordering, and pagination to our table! But there are several other configuration parameters that I typically like to include. They are specified within the DataTable() function.

table = $('#example').DataTable({
"lengthMenu": [ [15, 50, 100, -1], [15, 50, 100, "All"] ],
"pagingType": "simple",
scrollY: 400,
scrollCollapse: true,
order: [[ 0, 'asc' ], [3, 'desc' ]],
ajax{...},
columns: ...
})

To recap, I customized the options for how many entries the table can show, as well as the style of the pagination feature. I also added scrollY so that the table will have a scrollable body with fixed headers. And lastly, I defined ordering for the USER ID and COMPLETED columns once the data is loaded.

Here is what the table looks like now.

GIF by the author. Sample project table

Conclusion

We have successfully implemented the core elements that make our HTML table responsive, interactive, and linked to the server. This is just a base foundation, however, and much more complexity can now be layered on top.

Thank you for reading!

And once again, the sample project files are on GitHub.

--

--