I have a DataTables where I'm taking additional actions on the AJAX returned data, per the docs, like:
var table = $('#statstable').DataTable( {
ajax: function (data, callback, settings) {
$.ajax({
url: "/api/stats/2020/01/",
}).then ( function(json) {
var data = json;
$("#total_in_month").text(json.total_in_month);
callback(data);
});
},
search: false,
);
The source I'm using is formatted as such:
{
"total_in_month": 1636,
"data": [
{"total_on_date": 47, "date": "01-01-2020", "externals": 1},
{"total_on_date": 47, "date": "02-01-2020", "externals": 1},
{"total_on_date": 48, "date": "03-01-2020", "externals": 1},
{"total_on_date": 48, "date": "04-01-2020", "externals": 1},
{"total_on_date": 49, "date": "05-01-2020", "externals": 1},
{"total_on_date": 48, "date": "06-01-2020", "externals": 3},
{"total_on_date": 47, "date": "07-01-2020", "externals": 3},
{"total_on_date": 48, "date": "08-01-2020", "externals": 1},
...
]
}
Everything works, i.e. my DataTable is populated properly and the span total_in_month is updated properly when the page is loaded.
However I'd like to dynamically change the data in the table, but also in the span 'total_in_month' outside of the table.
So I was using something like $("#statstable").DataTable().ajax.url("/api/stats/" + year + "/" + month + "/").load();, which works, but that doesn't allow me to update total_in_month.
Any idea how this can be approached?
I tried calling $('#statstable').DataTable( { ajax: function (data, callback, settings) { ... again but that yields an error Cannot reinitialise DataTable.
table.ajax.reload();. Thereload()call will re-execute theajaxoption in your DataTable definition. It will fetch the latest data from the URL and also update the external span.table.ajax.url()followed by atable.ajax.reload()seems to have the same effect astable.ajax.url().load(). When re-doing the json request, I would like to receive the json data once, and update both the table /and/ the#total_in_monthspan, like I do with theajax: function (data, callback, settings)call when initially loading the table.table.ajax.reload()with the use of a variable for the URL. This avoids needing to usetable.ajax.url().