How do I initialize my table AFTER my data is retrieved from my backend?
How do I initialize my table AFTER my data is retrieved from my backend?
Hi all,
This is the second time I've run into this "issue," so I figured I'd make a post to ask for help.
On page load, I want to make a call to a Lambda function, which returns the formatted data for my table to the client.
data = callLambda()
$(function () {
$('#main-table').DataTable( {
data: data,
processing: true,
columns: [
{ title: "Name" },
{ title: "Symbol" },
{ title: "Rank" },
{ title: "Price" },
{ title: "Market Cap" }
]
});
});
My problem: the table initializes before the call to the Lambda returns, and I get errors/a blank table. I tried structuring my code to utilize callbacks, but I couldn't get it to work!
Last project I ended up throwing in the towel and manually putting a .5 second delay on drawing the table... but that felt like cheating and I'd love to learn how to properly setup my tables with a Lambda backend. If this design is fundamentally flawed, please please please tell me — I'm trying to improve as a developer.
Appreciate all the help you can provide, let me know if you need any other details.
This question has an accepted answers - jump to answer
Answers
You should probably use an event and put your function in there. The "xhr" event seems to be suitable.
https://datatables.net/reference/event/xhr
Here is an example from my own coding. I used the debugger a lot to figure out what data tables is really returning from the server. In my example I needed to do something with options read from the server.
How are you calling your lambda function? Are you using
$.ajax
or something similar? If the DataTable has already been initialised you can userows.add()
to add the data returned from the function.Allan
Sorry I'm late getting back to this, was not working on the project. Thanks for the replies.
While I decided to use an API that utilized my Lambda function, the concept is the same. For others — this was my end code.
QUESTION:
Is this good practice for a static website? Async call to API, wait for it to return, then populate the DataTable? Or should I try to preload the data before initializing the DataTable?
That's fine. You could just use
data: []
in the initialisation, rather than needing a variable for the empty array, since you don't actually do anything with it.However, you could use DataTables' own
ajax
for this:The
ajax.dataSrc
option will tell DataTables just to expect an array of data in the JSON, which it appears you are using.Allan