I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
I have been unable to delete a post via AJAX.
In my Dashboard routes file (routes\admin\dashboard.js
) I have:
// Delete Post
router.delete('/post/delete/:id', dashboardController.deletePost);
In my Dashboard controller:
exports.deletePost = (req, res, next) => {
const postId = req.params.id;
posts.findByIdAndRemove(postId, function(err){
if (err) {
console.log('Error: ', err);
}
res.sendStatus(200);
});
}
In the view that lists the post in a table, with and "Edit" and a "Delete" button for each one I have:
<% if (posts) { %>
<% posts.forEach(function(post) { %>
<tr data-id="<%= post._id %>" class="d-flex">
<td class="col-1"></td>
<td class="col-4 col-lg-5">
<%= post.title %>
</td>
<td class="col-2"></td>
<td class="col-2"></td>
<td class="col-3 col-lg-2 text-right">
<div class="btn-group">
<a href="#" class="btn btn-sm btn-success">Edit</a>
<a href="#" class="btn btn-sm btn-danger delete-post" data-id="<%= post._id %>">Delete</a>
</div>
</td>
</tr>
<% }); %>
<% } else { %>
<tr>
<td colspan="5">There are no posts</td>
</tr>
<% } %>
Finally in public\assets\js\admin.js
I have:
$(document).ready(function(){
$('.delete-post').on('click', function(evt){
evt.preventDefault();
let postId = $(this).data('id');
if(confirm('Delete this post?')) {
$.ajax({
url: '/post/delete/' + postId,
method: 'GET',
success: function(deleteMsg){
$('tr[data-id="' + postId +'"]').fadeOut('250');
}
});
}
});
});
I have that was enough for the delete operation to be successful, but it is not.
UPDATE:
If I replace url: '/post/delete/' + postId,
with url: '/dashboard/post/delete/' + postId,
I get a 500 internal server error
. I see posts is not defined
in the network tab.
What am I missing?