Reputation:
I use Pug/Jade templates to render my content in express.js. I want to create a infinite scroll on client side. When the user press a button, can I through an ajax call to append more contents to the same page using a Pug/Jade file?
I know that can return the results on client side and render them there, but I ask if it's possible on server side.
Something like this:
cliend-index.js
$('#load-more').click(function() {
$.ajax({
type: 'POST',
url: '/get_more_posts',
dataType: 'json',
data: {
last_received_id: last_received_id
},
success: function() {
// do nothing as the content rendered on the server side
},
error: function() {
// generate an error
}
});
});
sever-app.js
app.post('/get_more_posts', function(req, res) {
db.select_post({
last_received_id: req.body.last_received_id
}, function(query_res) {
res.render('more-posts', {
_POST_LIST: helper.prepare_posts_for_rendering(query_res)
});
});
});
Above the file more-posts used in render method, needs to append the data to index.pug which is my index file.
Do I use some block for this? Is it possible to render the html and return the content to client, so in the end I'll append it using JQuery?
Upvotes: 2
Views: 2662
Reputation:
Okay that was silly. All I wanted to do is to return the data from res.render()
to a variable and send this variable back to ajax call.
So in the end I use something like this:
app.post('/get_more_posts', function(req, res) {
db.select_post({
last_received_id: req.body.last_received_id
}, function(query_res) {
var rendered = res.render('more-posts', {
_POST_LIST: helper.prepare_posts_for_rendering(query_res)
});
res.status(200).send({ rendered: rendered });
});
});
and handle it in ajax.
Upvotes: 2
Reputation: 11177
Assuming you're returning partial html from the server, all you're missing is to append it on the client side. So if you want to add it to a an element #more-data
:
success: function(data) {
$('#more-data').html(data);
}
Upvotes: 1