Reputation: 3501
I am writing a Node.js + Express + express-handlebar app. I am reading my data from a MySQL database and displaying it in a table. I am implementing pagination functionality where on click of "next" button I make an ajax call to my node js server
$j('.btn-nxt').click(function(){
$j.ajax({
type: 'post',
url: '/',
data : {
action: 'next'
},
error: function(err) {
console.log('------------ Error while updating this resident: ' + err);
console.log('------------ Error while updating this resident: ' + err.message);
}
});
});
Below is my index.js route for my index.handlebars
index.js
var express = require('express');
var router = express.Router();
var callDatabase = require('../config/database.js');
var startIndex = 0;
var recordLimit = 10;
//home page route
router.get('/', function(req, res){
callDatabase.getResidents(req, res, startIndex, recordLimit);
});
router.post('/', function(req, res){
var data = req.body;
var action = data.action;
if(action == 'next') {
startIndex += recordLimit;
}
callDatabase.getResidents(req, res, startIndex, recordLimit);
res.redirect('/');
});
module.exports = router;
And this is database.js where I am making the actual call to my database
database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'dbname-db.rds.amazonaws.com',
user : 'username',
password : 'password',
port: '3306',
database : 'dbname',
multipleStatements: true,
dateStrings: true
});
var residentQuery = 'SELECT idResidents, name, primaryEmail FROM Residents LIMIT ';
exports.getResidents = function(req, res, startIndex, recordLimit) {
connection.query(residentQuery + startIndex + ',' + recordLimit, function(err, rows, fields) {
if (err) {
console.log('----------------------- ERROR: Error querying records - ' + err);
console.log('----------------------- ERROR: ' + err.message);
return err;
}
for(var i in rows) {
console.log('id: ' + rows[i].idResidents + ' name: ' + rows[i].name + ' email: ' + rows[i].primaryEmail);
}
res.render('index', {
title:'Test Node App',
dbrows: rows
});
});
}
When I run my app, the first 10 rows appear, when I click the next button, the ajax call is made and I can see the next 10 rows in the conslo.log of database.js. However my view does not get updated. I tried calling res.render('/') from both the route.post() of index.js and from database.js but it gives me an error saying - "Can't set headers after they are sent".
How do I refresh my table? I am using {{#each dbrows}}...{{/each}} to populate the rows.
Upvotes: 0
Views: 1675
Reputation: 3501
I reloaded the page from ajax itself using location.reload(). So when the next or previous pagination option is clicked, it goes to the ajax function which in turn calls the node server to get the next/previous set of data. In the same ajax function after data I added the success property - success: { location.reload() }, error: { .... }. Now it works like a charm.
Upvotes: 1