Skip to content

Commit 46191eb

Browse files
committed
add and delete post,comments dynamically using ajax
1 parent a0e19c0 commit 46191eb

File tree

186 files changed

+17496
-64
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

186 files changed

+17496
-64
lines changed

assets/js/home_post_comments.js

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
2+
// this class would be initialized for every post on the page
3+
// 1. When the page loads
4+
// 2. Creation of every post dynamically via AJAX
5+
6+
console.log("Script 2 loaded");
7+
8+
class PostComments{
9+
// constructor is used to initialize the instance of the class whenever a new instance is created
10+
constructor(postId){
11+
this.postId = postId;
12+
this.postContainer = $(`#post-${postId}`);
13+
this.newCommentForm = $(`#post-${postId}-comments-form`);
14+
15+
this.createComment(postId);
16+
17+
let self = this;
18+
// call for all the existing comments
19+
$(' .delete-comment-button', this.postContainer).each(function(){
20+
self.deleteComment($(this));
21+
});
22+
}
23+
24+
25+
createComment(postId){
26+
let pSelf = this;
27+
this.newCommentForm.submit(function(e){
28+
e.preventDefault();
29+
let self = this;
30+
31+
$.ajax({
32+
type: 'post',
33+
url: '/comments/create',
34+
data: $(self).serialize(),
35+
success: function(data){
36+
let newComment = pSelf.newCommentDom(data.data.comment);
37+
$(`#post-comments-${postId}`).prepend(newComment);
38+
pSelf.deleteComment($(' .delete-comment-button', newComment));
39+
40+
new Noty({
41+
theme: 'relax',
42+
text: "Comment published ajax!",
43+
type: 'success',
44+
layout: 'topRight',
45+
timeout: 1500
46+
47+
}).show();
48+
49+
}, error: function(error){
50+
console.log(error.responseText);
51+
}
52+
});
53+
54+
55+
});
56+
}
57+
58+
59+
newCommentDom(comment){
60+
// I've added a class 'delete-comment-button' to the delete comment link and also id to the comment's li
61+
return $(`<li id="comment-${ comment._id }">
62+
<p>
63+
64+
<small>
65+
<a class="delete-comment-button" href="/comments/destroy/${comment._id}">X</a>
66+
</small>
67+
68+
${comment.content}
69+
<br>
70+
<small>
71+
${comment.user.name}
72+
</small>
73+
</p>
74+
75+
</li>`);
76+
}
77+
78+
79+
deleteComment(deleteLink){
80+
$(deleteLink).click(function(e){
81+
e.preventDefault();
82+
83+
$.ajax({
84+
type: 'get',
85+
url: $(deleteLink).prop('href'),
86+
success: function(data){
87+
$(`#comment-${data.data.comment_id}`).remove();
88+
89+
new Noty({
90+
theme: 'relax',
91+
text: "Comment Deleted",
92+
type: 'success',
93+
layout: 'topRight',
94+
timeout: 1500
95+
96+
}).show();
97+
},error: function(error){
98+
console.log(error.responseText);
99+
}
100+
});
101+
102+
});
103+
}
104+
}

assets/js/home_posts.js

+155
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
{
2+
console.log("Script 1 Loaded");
3+
4+
// method to submit the form data of new post using ajax
5+
let createPost=function(){
6+
7+
let newPostForm=$('#new-post-form');
8+
9+
newPostForm.submit(function(e){
10+
11+
e.preventDefault();
12+
13+
$.ajax({
14+
type: 'post',
15+
url:'/posts/create',
16+
data: newPostForm.serialize(),
17+
success: function(data){
18+
19+
console.log(data);
20+
let newPost=newPostDom(data.data.post);
21+
22+
$('#posts-list-container>ul').prepend(newPost);
23+
24+
console.log("new post",newPost);
25+
26+
new Noty({
27+
theme:'relax',
28+
text: 'Post Created',
29+
type:'success',
30+
layout:'topRight',
31+
timeout:1500
32+
33+
}).show();
34+
35+
36+
deletePost($(' .delete-post-button' , newPost));
37+
38+
},error:function(error){
39+
40+
console.log(error.responseText);
41+
new Noty({
42+
theme:'relax',
43+
text:'Error in creating Post !',
44+
type:'error',
45+
layout:'topRight',
46+
timeout:1500
47+
})
48+
}
49+
50+
})
51+
});
52+
}
53+
54+
55+
// method to create a post in DOM
56+
57+
let newPostDom=function(post){
58+
return $(`<li id="post-${post._id}">
59+
<p>
60+
61+
<small>
62+
<a class="delete-post-button" href="/posts/destroy/${post._id}">X</a>
63+
</small>
64+
65+
${post.content}
66+
67+
<br>
68+
69+
<small>
70+
${post.user.name}
71+
</small>
72+
73+
</p>
74+
75+
<div class="post-comment">
76+
77+
78+
79+
<form action="/comments/create" method="POST">
80+
81+
<input type="text" name="content" placeholder="Type here to add comment..." required>
82+
<input type="hidden" name="post" value="${post._id}">
83+
<input type="submit" value="add comment">
84+
85+
</form>
86+
87+
88+
89+
<div class="post-comments-list">
90+
<ul id="posts-comments-${post._id}">
91+
92+
93+
</ul>
94+
</div>
95+
96+
</div>
97+
98+
</li> `)
99+
}
100+
101+
102+
// method to delete a post from DOM
103+
let deletePost=function(deleteLink){
104+
console.log("delete link",deleteLink)
105+
$(deleteLink).click(function(e){
106+
107+
e.preventDefault();
108+
109+
$.ajax({
110+
111+
type:'get',
112+
url:$(deleteLink).prop('href'),
113+
success:function(data){
114+
115+
console.log("data",data.data.post_id);
116+
117+
$(`#post-${data.data.post_id}`).remove();
118+
119+
new Noty({
120+
theme:'relax',
121+
type:'success',
122+
text:"Post deleted",
123+
layout:"topRight",
124+
timeout:1500
125+
}).show()
126+
127+
},error:function(error){
128+
console.log(error.responseText);
129+
}
130+
});
131+
132+
});
133+
}
134+
135+
136+
// loop over all the existing posts on the page (when the window loads for the first time) and call the delete post method on delete link of each, also add AJAX (using the class we've created) to the delete button of each
137+
let convertPostsToAjax = function(){
138+
$('#posts-list-container>ul>li').each(function(){
139+
let self = $(this);
140+
let deleteButton = $(' .delete-post-button', self);
141+
deletePost(deleteButton);
142+
143+
// get the post's id by splitting the id attribute
144+
let postId = self.prop('id').split("-")[1];
145+
console.log(postId);
146+
new PostComments(postId);
147+
});
148+
}
149+
150+
151+
convertPostsToAjax();
152+
createPost();
153+
154+
155+
}

controllers/comments_controller.js

+74-45
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,80 @@
1-
const Comment=require('../models/comment');
2-
const Post=require('../models/posts');
3-
4-
5-
module.exports.create=function(req,res){
6-
7-
Post.findById(req.body.post,function(err,post){
8-
9-
if(post){
10-
11-
Comment.create({
12-
13-
content:req.body.content,
14-
post:req.body.post,
15-
user:req.user._id
16-
17-
},function(err,comment){
18-
19-
// handle error
20-
21-
post.comments.push(comment);
22-
post.save();
23-
24-
res.redirect('/');
25-
});
26-
}
27-
28-
});
1+
const Comment = require('../models/comment');
2+
const Post = require('../models/posts');
293

30-
}
4+
module.exports.create = async function(req, res){
315

32-
module.exports.destroy=function(req,res){
33-
34-
Comment.findByIdAndDelete(req.params.id,function(err,comment){
35-
36-
37-
if(req.user.id==comment.user)
38-
{
39-
let postId=comment.post;
40-
comment.remove();
41-
Post.findByIdAndUpdate(postId,{$pull:{comments:req.params.id}},function(err,post){
42-
return res.redirect('back');
43-
});
44-
}
45-
else{
46-
return res.redirect('back');
6+
try{
7+
let post = await Post.findById(req.body.post);
8+
9+
if (post){
10+
let comment = await Comment.create({
11+
content: req.body.content,
12+
post: req.body.post,
13+
user: req.user._id
14+
});
15+
16+
post.comments.push(comment);
17+
post.save();
18+
19+
if (req.xhr){
20+
// Similar for comments to fetch the user's id!
21+
comment = await comment.populate('user', 'name').execPopulate();
22+
23+
return res.status(200).json({
24+
data: {
25+
comment: comment
26+
},
27+
message: "Post created!"
28+
});
29+
}
30+
31+
32+
// req.flash('success', 'Comment published!');
33+
34+
res.redirect('/');
4735
}
36+
}catch(err){
37+
req.flash('error', err);
38+
return;
39+
}
40+
41+
}
42+
4843

49-
})
44+
module.exports.destroy = async function(req, res){
5045

46+
try{
47+
let comment = await Comment.findById(req.params.id);
48+
49+
if (comment.user == req.user.id){
50+
51+
let postId = comment.post;
52+
53+
comment.remove();
54+
55+
let post = Post.findByIdAndUpdate(postId, { $pull: {comments: req.params.id}});
56+
57+
// send the comment id which was deleted back to the views
58+
if (req.xhr){
59+
return res.status(200).json({
60+
data: {
61+
comment_id: req.params.id
62+
},
63+
message: "Post deleted"
64+
});
65+
}
66+
67+
68+
// req.flash('success', 'Comment deleted!');
69+
70+
return res.redirect('back');
71+
}else{
72+
req.flash('error', 'Unauthorized');
73+
return res.redirect('back');
74+
}
75+
}catch(err){
76+
req.flash('error', err);
77+
return;
78+
}
79+
5180
}

0 commit comments

Comments
 (0)