Reputation: 5914
I am trying to send a DELETE request on a button click, but I'm not sure if my jQuery is set up and despite using routing that is for the delete method, I am still getting GET request errors Cannot GET /app/delete/1
. Am I on the right track with my jQuery and how do I prevent this GET request?
Route:
appRoutes.route('app/delete/:testId')
.delete(function(req, res){
models.Test.destroy({
where: {
userId: req.user.user_id,
testId: req.params.testId
}
}).then(function(){
res.redirect('/app');
});
});
Link:
<a href="/app/delete/{{test.testId}}" id="test-delete-link">Delete</a>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#test-delete-link').click(function(){
$.ajax({
type: 'DELETE',
url: '/app/delete/{{test.testId}}'
});
});
});
</script>
Upvotes: 0
Views: 1363
Reputation: 1498
The issue is that when a link is clicked, it uses GET
. When your link is clicked, two things are happening.
click
event is triggered and jQuery sends the DELETE
request.GET
request to the same path because it is a link.To fix this, set the href
property of the link to "javascript:void(0);"
. This makes it so that clicking the link does nothing except what is specified in the click
event.
As a side note, I would change the path of the request from /app/delete/:testId
to /app/:testId
. The way it is right now is redundant, as you are saying DELETE /app/delete/1
. The more RESTful way to do it is DELETE /app/1
.
Upvotes: 5