How to reload table with new data?
How to reload table with new data?
Debugger code (debug.datatables.net):
<script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css">
<input type="text" id="textinput" name="textinput"><br><br>
<div class="container">
<div class="row">
<div class="col-sm-12">
<table id="example" class="display" width="100%"></table>
</div>
</div>
</div>
<script>
var textInput = document.getElementById('textinput')
var dataSet = [
[ "Tiger Nixon", "System Architect", "Edinburgh", ],
[ "hello Nixon", "System Architect", "Edinburgh", ],
[ "Tiger Nixon", "System Architect", "Edinburgh", ],
];
var table
$(document).ready(function() {
table = $('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
],
searching: false,
paging: false,
info: false
} );
} );
dataSet.push(['1','2','3']) //add new row to data
//problem occurs here!
setTimeout(() => { table.ajax.reload(); }, 2000); //wait some time and reload table
</script>
Error messages shown:
jquery.dataTables.min.js:36 Uncaught TypeError: Cannot set property 'data' of null
Description of problem: Im trying to create a table with some predefined data in it. Afterwards I want to reload the table with some new data. Does anyone know what I am doing wrong here?
I should point out that I am using this as test code before I try to implement a table reload function with user entered data and an event listener.
Many thanks in advance!
This question has accepted answers - jump to:
Answers
The data isn't being loaded by ajax, there isn't an
ajax
property, which means you then can't reload it withajax.reload()
,You can just add that new row to the table with
row.add()
:Colin
That makes sense, thanks for your help Colin!
Is it possible to reload the entire table once original dataset has been modified, e.g.
Use
rows.add()
to add multiple rows from an array, like this:Note you are missing the leading g
[
for the array.Kevin
Hi Kevin,
Thanks for your reply.
I am actually trying redraw the entire table rather than add new rows to the existing table. So the new table should ideally contain only the new data (2 rows) if that makes sense. Do you know if this is possible?
Cheers,
Dee
If you are using the
data
option to initially load the table then useclear()
to remove all the rows followed by therows.add()
.Kevin
It's also worth noting you may want/need to redraw the table after loading and that you can chain the clear, add and draw together.
Thanks for your help, the last two suggestions worked for me!