Hello. Does it has any event to count DataTables item after I reload DataTable successfully or any other way to do it?
Here is my DataTable script :
var table = $('#prizeitem-table').DataTable({
processing: true,
serverSide: false,
pageLength: 10,
ajax: '{{ route('prizeitems.index') }}',
columns: [
{data: 'id', title: 'Id'},
{data: 'code', title: 'Code'},
{data: 'name', title: 'Name'},
],
order: [[0, 'desc']]
});
DataTable reload script :
table.ajax.reload();
DataTable count item script :
if (!table.data().any()) {
alert('Data is empty');
}
I put this 2 script together like this :
table.ajax.reload();
if (!table.data().any()) {
alert('Data is empty');
}
But the count item script was run before the DataTable finish reload the data. So, I got the result was an old data before the ajax reload.
Please help me.
Hello, You can try this:
var table = $('#example').DataTable();
var data = table.rows().data();
alert( 'The table has '+data.length+' records' );
If this not working to you, try use "initComplete" method to make a callback function after your datatable is ready!! If you need get the count after every action use "drawCallback".
Let me know if it works 馃槃
Or access the ajax json response.
table.ajax.json().recordsTotal
Sorry for replying lately.
I try @DanielGilB code and put inside initComplete and drawCallback function. Both of them successfully works.
initComplete
initComplete: function(settings, json) {
alert(table.rows().data().length);
}
drawCallback
drawCallback: function(settings) {
var api = this.api();
alert(api.rows().data().length);
}
I also try Sir @yajra code and put inside initComplete function, it also successfully works. But when try inside drawCallback function like this
drawCallback: function(settings) {
var api = this.api();
alert(api.ajax.json().recordsTotal);
}
I got this error
TypeError: api.ajax.json(...) is undefined
By the way, thank you to @DanielGilB and Sir @yajra have answered my question and helped me.
table= $('#example').DataTable();
$('#example').on('draw.dt', function() {
console.log(table.ajax.json().recordsTotal);
});
Most helpful comment