Populate table from GET request
Populate table from GET request
Hi, this might be a stupid question but I've spent the last 2 hours googling and looking through the forum without finding a solution... So I thought maybe I'm just not asking the right things.
I want to have a table that is populated by the result of a GET request to my API. Before, I was using a jinja2 template to populate the table before returning it to the client, but now I would like to just have an empty table in the HTML that is populated via ajax request when the page is loaded. Sounds simple enough.
The returned json object is of style:
[
{
"column1": "data1",
"column2": "data2"
},
{
"column1": "data1",
"column2": "data2"
}
]
However, any examples I find (e.g. https://datatables.net/examples/data_sources/index.html) always point to static files as a source and not the result of a get request. Below are the relevant snippets.
<div>
<table id="my_table" class="display">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
<script
<!- Script shown below ->
</script>
$(document).ready( function () {
var table = $('#my_table').DataTable({
ajax: {
url: '/my/api/endpoint',
type: 'GET'
});
I assume, that there are some config parameters missing to tell the datatable to query the endpoint and then parse the data to the table.
Answers
Did you take a look at the api documentation?
https://datatables.net/reference/api/
And these examples?
https://datatables.net/examples/ajax/index.html
You can remove the empty
thead
andtbody
tags. Your row data are objects so you will usecolumns.data
to define the columns. Also usecolumns.title
to build thethead
. Something like this:Kevin
@rf1234 Yes I did. All examples I found only refer to using files as a data source but not a get request.
@kthorngren Thanks for the example! I applied it but nothing changed. On my server I see that only the page request is ever sent, but not the data request which goes to a different endpoint). The "data endpoint" is available, since I can use a regular ajax request to fetch data from there.
Is there some way to feed this result to the table? I did try something like this after the table initialization, but it's not doing anything.
They are actually fetching the data via Ajax. You can see the result in the Ajax tab. Plus you can use the browser's Network Inspector tool to see the Ajax request and response.
I forgot one thing. Since your data is not in the
data
object as described in the Ajax docs you will need to useajax.dataSrc
like the second example.Yes, that should work. Remove the
ajax
option but leave thecolumns
config. Likely the response is a JSON string not a Javascript object. You might need to usedata = JSON.parse(data);
beforerows.add()
.Kevin