Skip to content

Commit 4cb9f02

Browse files
Krishna KantKrishna Kant
Krishna Kant
authored and
Krishna Kant
committed
Using jQuery AJAX for Not reaload whole Page
1 parent c536332 commit 4cb9f02

File tree

8 files changed

+268
-9
lines changed

8 files changed

+268
-9
lines changed

Diff for: assets/js/home_post_comments.js

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

Diff for: assets/js/home_posts.js

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
{
2+
let createPost = ()=> {
3+
let newPostForm = $('#new-post-form');
4+
5+
newPostForm.submit((e)=> {
6+
e.preventDefault();
7+
8+
$.ajax({
9+
type: 'post',
10+
url: '/posts/create',
11+
data: newPostForm.serialize(),
12+
success: function(data) {
13+
let newPost = newPostDom(data.data.post);
14+
$('#posts-list-container>ul').prepend(newPost);
15+
16+
deletePost($(' .delete-post-button', newPost));
17+
18+
// Call the Create Comment Clsss
19+
new PostComments(data.data.post._id);
20+
21+
new Noty({
22+
theme: 'relax',
23+
text: "Post published!",
24+
type: 'success',
25+
layout: 'topRight',
26+
timeout: 1500
27+
28+
}).show();
29+
},
30+
error: function(error){
31+
console.log(error.responseText);
32+
}
33+
})
34+
})
35+
}
36+
37+
38+
let newPostDom = (post)=> {
39+
return $(`
40+
<li id="post-${post._id}">
41+
<p>
42+
<small>
43+
<a class="delete-post-button" href="/posts/destroy/${ post._id }">X</a>
44+
</small>
45+
46+
${ post.content }
47+
<br>
48+
<small>
49+
${ post.user.name }
50+
</small>
51+
</p>
52+
53+
<div class="post-comments">
54+
55+
<form id="post-${ post._id }-comments-form" action="/comments/create" method="POST">
56+
<input type="text" name="content" placeholder="Type Here to add comment..." required>
57+
<input type="hidden" name="post" value="${ post._id }" >
58+
<input type="submit" value="Add Comment">
59+
</form>
60+
61+
62+
<div class="post-comments-list">
63+
<ul id="post-comments-${ post._id }">
64+
65+
</ul>
66+
</div>
67+
</div>
68+
</li>
69+
`)
70+
};
71+
72+
// Method for Delete a Post from DOM
73+
let deletePost = (deleteLink)=>{
74+
$(deleteLink).click((e)=> {
75+
$.ajax({
76+
type: 'get',
77+
url: $(deleteLink).prop('href'),
78+
success: function(data){
79+
$(`#post-${data.data.post_id}`).remove();
80+
81+
new Noty({
82+
theme: 'relax',
83+
text: "Post Deleted",
84+
type: 'success',
85+
layout: 'topRight',
86+
timeout: 1500
87+
88+
}).show();
89+
},
90+
error: function(error){
91+
console.log(error.responseText);
92+
}
93+
})
94+
})
95+
}
96+
97+
98+
99+
// 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 have Created) to deleted button of Each
100+
let convertPostsToAjax = ()=> {
101+
$('#posts-list-container>ul>li').each(()=> {
102+
let self = $(this);
103+
104+
let deleteButton = $(' .delete-post-button', self);
105+
deletePost(deleteButton);
106+
107+
108+
// Get the Post's Id by Splitting the ID Attribute
109+
let postId = self.prop('id').split("-")[1]
110+
new PostComments(postId);
111+
})
112+
};
113+
114+
115+
createPost();
116+
convertPostsToAjax();
117+
}

Diff for: controllers/commentsController.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ module.exports.create = async (req, res)=> {
1515
post.comments.push(comment);
1616
post.save();
1717

18+
if(req.xhr) {
19+
comment = await comment.populate('user', 'name');
20+
21+
return res.status(200).json({
22+
data: {
23+
comment: comment
24+
},
25+
message: "Comment created!👍"
26+
});
27+
}
28+
1829
req.flash('success', 'Comment published!');
1930
return res.redirect('/');
2031
}
@@ -36,7 +47,15 @@ module.exports.destroy = async(req, res)=> {
3647
await Post.findByIdAndUpdate(postId, {
3748
$pull: {comments: req.params.id}});
3849

39-
req.flash('success', 'Comment deleted!');
50+
if (req.xhr){
51+
return res.status(200).json({
52+
data: {
53+
comment_id: req.params.id
54+
},
55+
message: "Comment deleted!👍"
56+
});
57+
}
58+
req.flash('success', 'Comment deleted!👍');
4059
return res.redirect('back');
4160
} else {
4261
req.flash('error', 'Unauthorized');

Diff for: controllers/postsController.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,21 @@ const Comment = require('../models/comment');
44

55
module.exports.create = async (req, res)=> {
66
try {
7-
await Post.create({
7+
let post = await Post.create({
88
content: req.body.content,
99
user: req.user._id
1010
});
1111

12+
if(req.xhr) {
13+
post = await post.populate('user', 'name');
14+
return res.status(200).json({
15+
data: {
16+
post : post
17+
},
18+
message: "Post Created!👍"
19+
})
20+
}
21+
1222
req.flash('success', 'Post published!');
1323
return res.redirect('back');
1424

@@ -28,6 +38,15 @@ module.exports.destroy = async (req, res)=> {
2838

2939
await Comment.deleteMany({post: req.params.id});
3040

41+
if(req.xhr) {
42+
return res.status(200).json({
43+
data: {
44+
post_id: req.params.id
45+
},
46+
message: "Post Deleted!👍"
47+
})
48+
}
49+
3150
req.flash('success', 'Post and associated comments deleted!');
3251
return res.redirect('back');
3352
} else {

Diff for: views/_comment.ejs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<li>
1+
<li id="comment-<%= comment._id %>">
22
<p>
33
<% if (locals.user && locals.user.id == comment.user.id){ %>
44
<small>

Diff for: views/_post.ejs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
<li>
1+
<li id="post-<%= post._id %>">
22
<p>
33
<% if(locals.user && locals.user.id == post.user.id) { %>
44
<small>
5-
<a href="/posts/destroy/<%= post.id %>">X&ensp;</a>
5+
<a class="delete-post-button" href="/posts/destroy/<%= post.id %>">X&ensp;</a>
66
</small>
77
<% } %>
88
<%= post.content %>
@@ -14,7 +14,7 @@
1414

1515
<div class="post-comments">
1616
<% if(locals.user){ %>
17-
<form action="/comments/create" method="post">
17+
<form id="post-<%= post._id %>-comments-form" action="/comments/create" method="post">
1818
<input type="text" name="content" placeholder="Type here to add comment..." required>
1919
<input type="hidden" name="post" value="<%= post._id %>">
2020
<input type="submit" value="Add Comment">

Diff for: views/home.ejs

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,6 @@
3434
</section>
3535
</div>
3636

37-
<script>
38-
console.log(posts);
39-
</script>
37+
<!-- importing this script for creating the comments -->
38+
<script src="/js/home_post_comments.js" ></script>
39+
<script src="/js/home_posts.js"></script>

Diff for: views/layout.ejs

+4
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
/>
1010
<script src="https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.4/noty.min.js"></script>
1111

12+
<!-- Jquery CDN Link -->
13+
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
14+
15+
<!-- External stylesheet -->
1216
<link rel="stylesheet" href="/css/layout.css" />
1317
<link rel="stylesheet" href="/css/header.css" />
1418
<link rel="stylesheet" href="/css/footer.css" />

0 commit comments

Comments
 (0)