Series: Datatables with Nodejs ,Express and Mongodb.Part4: Handle datatable serverside requests.

Deepika Gunda
2 min readMay 15, 2018
Photo by rawpixel on Unsplash

Every time a user loads the index.html ,datatables fires a POST request with all the parameters such as records requested by user , where to start the request from ,how many records to be returned etc.

So at the server-side, we read these parameters from the request . Inspect from chrome to look at how the request looks .

go to Fn+F12,network and look for the request parameters from chrome.

Hope you have your local machine setup to run the code. If not, download it from here .

In the server.js ,added a line to handle the route /populateZipCodes.

app.post('/populateZipCodes',HomeController.getZipCodes);

In the controller home.js we will handle the search request this way .We will look for the search term in city ,state or in the zipcode values. If values match even partially,we return those rows.

var searchStr = req.body.search.value;
if(req.body.search.value)
{
var regex = new RegExp(req.body.search.value, "i")
searchStr = { $or: [{'_id':regex },{'city': regex},{'state': regex }] };
}
else
{
searchStr={};
}

I am using Mongoose to talk with Mongodb, for every response to be returned ,we need to send the total number of results possible ,the number of results that got filtered because of the search criteria , and lastly the result rows itself.Snippet from the code below.

zipcodesModel.count({}, function(err, c) {
recordsTotal=c;
zipcodesModel.count(searchStr, function(err, c) {
recordsFiltered=c;
console.log(req.body.start);
console.log(req.body.length);
zipcodesModel.find(searchStr, '_id city pop state',{'skip': Number( req.body.start), 'limit': Number(req.body.length) }, function (err, results) {
if (err) {
console.log('error while getting results'+err);
return;
}

How we send the data back..

var data = JSON.stringify({
"draw": req.body.draw,
"recordsFiltered": recordsFiltered,
"recordsTotal": recordsTotal,
"data": results
});
res.send(data);

Thats it , the data is received and rendered .

The recordsFiltered ,recordsTotal are shown below the table .

RecordsTotal mentioned here.

Thats it folks! I am sure this series will help people picking up javascript ,nodejs and get super quick interactive tables with datatables!

Clap to show that you like this article and want more such articles.

Go to Part3 if you have missed it.

--

--

Deepika Gunda

I am a Software Engineer n Tech Enthusiast . You will see me publishing articles on Javascript, NodeJS and misc.