Skip to content

Instantly share code, notes, and snippets.

@fedeolto
Created February 7, 2018 10:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedeolto/3027f22147d8e1fcb66ac5f773d23a12 to your computer and use it in GitHub Desktop.
Save fedeolto/3027f22147d8e1fcb66ac5f773d23a12 to your computer and use it in GitHub Desktop.
jQuery DataTable Server-side processing with ExpressJs. In this very basic example let's forget for a moment about filtering and ordering
baseRouter.get('/fruitsList', (req, res) => {
/*
DataTable when Server-side processing is true sends the data it needs in the query string as you can
see in the network tab of any web inspector filtering GET XHR requests.
remember to always parse integer parameters to avoid any possible SQLinjection or XSS attack
(as DataTable Server-side processing documentation recommend too)
*/
var draw = parseInt(req.query.draw);
var start = parseInt(req.query.start);
var length = parseInt(req.query.length);
/*
following function calls some REST api performing the query in the db like
`/api/v1/fruits?limit=${length}&offset=${start}`
or performs some query like
SELECT TOP `length` name, color, description FROM fruits WHERE id >= `start`
*/
var fruitsList = await FruitsEndpoint.getFruitsList(start, length);
/*
following function calls some REST api performing the query in the db like
`/api/v1/fruits/length
or performs some query like
SELECT count(*) FROM fruits
because DataTable needs it to perform pagination
*/
var totalFruitsLength = await FruitsEndpoint.getTotalFruitsLength();
var fruitsListForFrontend = {
draw: draw,
recordsTotal : totalFruitsLength,
recordsFiltered : totalFruitsLength,
data: fruitsList
};
res.send(fruitsListForFrontend);
});
<table id="fruitsTable">
<thead>
<tr>
<th>name</th>
<th>color</th>
<th>description</th>
</tr>
</thead>
</table>
$(document).ready(
function () {
$('#fruitsTable').DataTable( {
'processing': true,
'serverSide': true,
'ajax': '/fruitsList',
'columns': [
{ 'data': 'name' },
{ 'data': 'color' },
{ 'data': 'description' }
]
});
}):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment