Osiris
Osiris

Reputation: 107

NodeJs delete request via jQuery/ajax

I have this code on server side

 router.delete('/categories/delete/:id', function(req,res){
         var id = req.params.id;
          Category.remove({_id: id},function(err){
               if(err){
                    console.log(err);
               }
               req.flash('success','Category Deleted');
               res.location('/manage/categories');
               res.redirect('/manage/categories');
          });
    });

In dustjs view I have this button <a href="#" class="removeCategory button tiny alert" data-id="{._id}">Delete</a>

And in the script file i have

$(document).ready(function(){
    $('.removeCategory').on('click', function(e){
        $target =  $(e.target);
        var id = $target.attr('data-id');
        $.ajax({
            type: 'DELETE',
            url: '/manage/categories/delete/'+id,
            success: function(response){
                alert('Delete');
                window.location = '/manage/categories';
            },
            error: function(err){
                console.log(err);
            }

        });
    });

});

The thing is that it kinda works but the category disappears only after I refresh the page but when i have look at the console I get a message like this:

abort: function abort()
​
always: function always()
​
complete: function add()
​
done: function add()
​
error: function add()
​
fail: function add()
​
getAllResponseHeaders: function getAllResponseHeaders()
​
getResponseHeader: function getResponseHeader()
​
overrideMimeType: function overrideMimeType()
​
pipe: function then()
​
progress: function add()
​
promise: function promise()
​
readyState: 4
​
responseText: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /manage/categories</pre>\n</body>\n</html>\n"
​
setRequestHeader: function setRequestHeader()
​
state: function state()
​
status: 404
​
statusCode: function statusCode()
​
statusText: "Not Found"
​
success: function add()
​
then: function then()

I also want to mention that the alert box never appears. Does anyone know how to fix this issue? Thank you in advance

Upvotes: 0

Views: 2238

Answers (1)

b3nc1
b3nc1

Reputation: 106

seems like the url you are calling is not correct, the responseText property gives a hint on that:

Cannot DELETE /manage/categories

thats why your error Handler is called:

error: function(err){
  console.log(err);
}

and not the success.

Are you sure the id is determined correct?

Upvotes: 1

Related Questions