My table is dynamically generated using Thymeleaf and I want to update its contents with jQuery.
<table class="table table-hover" id="main-table">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep date</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" id="repDate" th:text="${@findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
<td class="text-center" id="hashrate" th:text="${@findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
</tr>
</tbody>
</table>
To refresh the table every 8 seconds, I have created this function:
$(document).ready(function() {
var table = $('#main-table').DataTable({
ajax: {
url: '/refresh',
dataSrc:''
},
paging: true,
lengthChange: false,
pageLength: 20,
stateSave: true,
info: true,
searching: false,
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] }
],
"order": [[ 0, "asc" ]]
});
setInterval(function(){
table.ajax.reload();
}, 8000);
});
This is the JSON response received:
[{
"id":1,
"repDate":{
"offset":{ },
"nano":880042000,
"year":2018,
"monthValue":4,
"dayOfMonth":25,
"hour":12,
"minute":58,
"second":53,
"month":"APRIL",
"dayOfWeek":"WEDNESDAY",
"dayOfYear":115
},
"hashrate":5114926.0
},...more entries
]
Despite following your advice, I am encountering an error message:
Uncaught TypeError: Cannot read property 'reload' of undefined
I also receive a warning popup that says:
Data Tables warning: table id=main-table - Requestem unknown parameter '0' for row 0 column 0. For more information about this error, please see: http://datatables.net/tn/4
EDIT
I have moved the table declaration outside the function but the warning persists.
EDIT 2
Following your instructions, the data now refreshes successfully. However, there are still some issues present.
Firstly, the stateSave: true
property no longer works, causing the table to always reset to the first page upon reload.
Secondly, I have lost all styling such as class="text:center"
and the on:click
functionality originally included in my HTML file.