I have done all your suggestions with some edits as per the response requirements and it is now working fine.Now the problem I am getting is with the like buttons that comes associated with the posts.I tried to recognize them with data-id attributes but everytime I click a particular button It's updating only in the 1 st P tag likes count.In the database also it affects only that 1st post besides using data-id to distinguish.I am not sure about my usage of data-id because this is the 1st time I am trying it.Please correct me with it,if wrong and help me associate the update likescount action with each of the looped button.I will update my code sample along with the response I get on my console.Please help me with it.
log on the console
(3) [{…}, {…}, {…}]0: {_id: "5b2673ed3e6a8e0c749b4c32", body: "kjhdishduishduihsduishduishdui shdishduihsuidsuids…opdksaodkjsa ↵dskjdiosajd ↵dsjadoisad ↵dsaoijdisa", author: "5b206e07e850480d50861f75", title: "simple post to test likes", __v: 0, …}1: {_id: "5b2073b7517e2b1760ffbbfd", body: "Quisque velit nisi, pretium ut lacinia in, element…da. Cras ultricies ligula sed magna dictum porta.", author: "5b206e07e850480d50861f75", title: "nodejs", __v: 0, …}2: {_id: "5b2073ad517e2b1760ffbbfc", body: "Quisque velit nisi, pretium ut lacinia in, element…da. Cras ultricies ligula sed magna dictum porta.", author: "5b206e07e850480d50861f75", title: "test", __v: 0, …}
main.js
$('.likeicon').on('click',() => {
var id = $('.likeicon').attr('data-id');
$.ajax({
url:'/forum/addlikes/'+id,
method:"POST"
});
});
refresh();
});
function refresh(){
$.ajax({
url: "/forum/getlikes/",
contentType: "application/json",
method: "GET",
success: function(response) {
// console.log(response);
$.each(response, function(index) {
// console.log(response[index].likes);
$(".likes-" + response[index]._id).first().html( response[index].likes );
});
setTimeout(refresh, 500);
}
});
}
index.pug
extends layout
block content
h1 #{title}
ul.list-group
each post, i in posts
li.list-group-item
a(href="/forum/"+post._id+"?"+post.author)= post.title
div #{post.body}
button(data-id=post._id class='likeicon' value=post._id) LIKE
p(class='likes-'+post._id)
post_routes.js
router.get('/getlikes/',(req,res) => {
Post.find({},(err, posts) => {
if(err){
console.log(err);
} else {
posts = posts.slice(0).reverse();
res.send(posts);
}
});
})
router.post('/addlikes/:id',(req,res) => {
Post.findById(req.params.id,(err,post) => {
if(err) throw err;
else{
post.likes+=1;
post.save((err) =>{
if(err) throw err;
else{
console.log(post.likes);
}
});
}
});
});
Please help me with this alone.I am almost done.Thanks in advance.