How to refresh a datatable that sources its data from localStorage, without reloading the tabpage?
How to refresh a datatable that sources its data from localStorage, without reloading the tabpage?
Please refer to the following test case:
http://58.64.211.82/Ed/examples/advanced/localStore.html
The full html and javascript source are already available via the "View page source" of the browser; no server-side script or SQL required.
All I wanna do are:
- Load the localStorage with some data
- Have the datatable source its data from the localStorage, which has just been loaded up from step 1.
- Refresh the datatable so that it would display out the relevant data mentioned in step 1 and 2.
For step 3, I call the $("#example").DataTable().draw() method in an attempt to make the datatable show up the data, but I wasn't able to make that happen.
In the test case (link provided above), the "Draw Table" button would load the localStorage up with some data and then call the $("#example").DataTable().draw() method, hoping the data would appear. However, the data would only show up after reloading the browser tabpage, and they do show up nicely in the datatable after the reload.
Please could you let me know how to redraw the datatable such that it would display out those data from the localStorage without the need to reload the browser tabpage?
Replies
.draw() won't refresh table data. You could have a function like the following
--- or ---
Check out https://datatables.net/reference/api/rows().invalidate() .
Please note that the first handles newly added or removed data where the invalidate just performs the re-rendering of data already in table.
jr42.gordon is absolutely spot on. Basically the issue in your button's event handler is that it assigns the value read from localStorage to a variable, but that variable isn't given to DataTables at all.
You could use:
which would do that.
Regards,
Allan
Thanks Allan and jr42.gordon for your response and help.
I'm still having a bit of an issue on my side. After giving the data in the variable (tobedone) to the datatable and then calling the .draw() method, the data still don't show up until the browser page has reloaded, which is obviously the very, very last resort.
Please see the updated version from the following link:
http://58.64.211.82/Ed/examples/advanced/localStore2.html
Please kindly advise me what is still missing from the code.
Thanks a lot.
tobedone
is an object, not an array. If you take a look at the documentation for therows.add()
method that you are using you will see that it accepts an array.You are using
$.map
when you pass data intodata
in the table constructor, which converts the data to an array. You need to do the same here.Allan
Thanks so much, Allan. Your method works perfectly.