Series: Datatables with Nodejs ,Express and Mongodb. Part 3:Connect datatables with serverside.
Datatables can display any json data being sent to it from the backend.So it fires a POST request to get data to display . Datatables can be customized to show paging ,ordering,searchbox. And when a user does these actions , datatables fires a post request and our backend needs to handle it. We will learn how to do all that here.
Hope you have your local machine setup to run the code. If not, download it from here .
Lets look at index.html ,where we write the script to initialize datatables on our zipcodesTable.
$(document).ready(function () {
var t = $('#ZipcodesTable').DataTable({
"paging": true,
"pageLength": 10,
"processing": true,
"serverSide": true,
'ajax': {
'type': 'POST',
'url': '/populateZipCodes'
},
'columns':
[
{ 'data': '_id', "defaultContent": "", 'name': 'ZipCode' },
{ 'data': 'city', "defaultContent": "", 'name': 'City' },
{ 'data': 'pop', "defaultContent": "", 'name': 'Population' },
{ 'data': 'state', "defaultContent": "", 'name': 'State' }
],
"columnDefs": [
{
"searchable": false,
"orderable": false,
"targets": 0
}
]});
By the above customization ,we are setting up paging for getting limited records instead of getting everything , serverside i.e sending all requests to the server , ajax — this is used to make a post request to the server using the route — populateZipCodes and columns is used to map the data being returned with the columns in the html table, pagelength to set the number of entries to be shown per page.
Similarly ,we can setup the ordering of columns etc.
Once we setup the customizations that we need on the datatable, we need to handle the requests in the server. Lets look at it more closely in our next Part.i.e Part4.
Part4: Handle datatable serverside requests.
Missed Part2. Check here.