DataTable is very powerfull and light weight tool to bind data in table.
In this article will learn How to bind server side data in table with pagination using jquery DataTable and How to dynamically bind data with pagination.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.13.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<table id="grid">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Contact No</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<script>
$(function () {
bindTable();
});
function bindTable() {
var colms = [
{
"render": function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}
},
{ data: 'name' },
{ data: 'contactNo' },
// we can also write data field as
//{
// "render": function (data, type, row) {
// return row.contactNo
// }
//}
{ data: 'email' },
{
"render": function (data, type, row) {
return `<a target='_blank' href='/abc'>View</a>`;
}
}
];
$('#grid').DataTable({
"processing": false,
"serverSide": true,
"filter": false,
"orderMulti": false,
"pageLength": 20,
"paging": true,
"lengthChange": false,
"columns": columns,
"ordering": false,
"ajax": {
"url": 'apiUrl',
"type": 'POST',
"contentType": "application/json; charset=utf-8",
"datatype": "JSON",
"data": function (dtParam) {
postData.pageNo = dtParam.draw;
postData.pageSize = dtParam.length;
return JSON.stringify(postData);
},
"dataFilter": function (res) {
var jsonResponse = jQuery.parseJSON(res);
var jsonNew = {};
jsonNew.draw = jsonResponse.data.paging.pageNo;
jsonNew.recordsTotal = jsonResponse.data.paging.totalRows;
jsonNew.recordsFiltered = jsonResponse.data.paging.totalRows;
jsonNew.data = jsonResponse.data.data;
return JSON.stringify(jsonNew);
},
"dataSrc": 'data',
"complete": function () {
loader.hide();
},
"error": function () {
toastr.error();
loader.hide();
}
}
});
}
</script>
</body>
</html>
{ data: 'email' } here email is the json object property returned from api response.
json object property name and name defined in data object should be same.
"data": function (dtParam){
postData.pageNo = dtParam.draw;
postData.pageSize = dtParam.length;
return JSON.stringify(postData);
}
dtParam have all the properties of datatable. in the data function we can define own properties.
"dataFilter": function (res) {
var jsonResponse = jQuery.parseJSON(res);
var jsonNew = {};
jsonNew.draw = jsonResponse.data.paging.pageNo;
jsonNew.recordsTotal = jsonResponse.data.paging.totalRows;
jsonNew.recordsFiltered = jsonResponse.data.paging.totalRows;
jsonNew.data = jsonResponse.data.data;
return JSON.stringify(jsonNew);
}
dataFilter is used to read json returned from api and can return new json object with own properties.