jQuery DataTables: "Load more" button - Server-side processing
Example for article at https://www.gyrocode.com/articles/jquery-datatables-load-more-button/
by gyrocode
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.15/datatables.min.css">
<script src="https://cdn.datatables.net/v/dt/dt-1.10.15/datatables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>
<script src="https://gyrocode.github.io/jquery-datatables-pageLoadMore/1.0.2/js/dataTables.pageLoadMore.min.js"></script>
<h3><a href="https://www.gyrocode.com/articles/jquery-datatables-load-more-button/" target="_blank">jQuery DataTables: "Load more" button</a> <small>Server-side processing</small></h3>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
<div class="dt-more-container">
<button id="btn-example-load-more" style="display:none">Load More</button>
</div>
<hr><a href="https://www.gyrocode.com/articles/tag/jquery-datatables/" target="_blank">See more articles about jQuery DataTables</a> on <a href="https://www.gyrocode.com/articles/" target="_blank">Gyrocode.com</a>
<script>
// FOR DEMONSTRATION ONLY:
// The code below is used for emulation of server-side processing
// and is not needed in production
$.mockjax({
url: '/test/0',
responseTime: 200,
response: function(settings){
var val = settings.data.start;
this.responseText = {
data: [],
draw: settings.data.draw,
recordsTotal: 100000,
recordsFiltered: 100000
};
for(var i = 0; i < settings.data.length; i++){
var index = (i + settings.data.start + 1);
this.responseText.data.push(["A" + index, "B" + index, "C" + index, "D" + index, "E" + index, "F" + index]);
}
}
});
</script>
CSS
.dt-more-container {
text-align:center;
margin:2em 0;
}
JavaScript
$(document).ready(function (){
var table = $('#example').DataTable({
dom: 'frt',
serverSide: true,
processing: true,
ajax: $.fn.dataTable.pageLoadMore({
url: '/test/0'
}),
drawCallback: function(){
// If there is some more data
if($('#btn-example-load-more').is(':visible')){
// Scroll to the "Load more" button
$('html, body').animate({
scrollTop: $('#btn-example-load-more').offset().top
}, 1000);
}
// Show or hide "Load more" button based on whether there is more data available
$('#btn-example-load-more').toggle(this.api().page.hasMore());
}
});
// Handle click on "Load more" button
$('#btn-example-load-more').on('click', function(){
// Load more data
table.page.loadMore();
});
});