Created
February 7, 2018 10:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<table id="fruitsTable"> | |
<thead> | |
<tr> | |
<th>name</th> | |
<th>color</th> | |
<th>description</th> | |
</tr> | |
</thead> | |
</table> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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