Trying to understand why after my destroy route is called below, that on the client side (jQuery) my .done() method does not run, despite being a part of my ajax call?
My Desired Behavior:
My /:id/destroy
route should run, destroy the quote by id, and then query all the existing quotes in the db. This should be handed back in the jQuery .done() method to be appended to existing HTML data (to display the new quotes without ever having to reload the page).
What's Happening Instead:
When the destroy route runs, the json data is returned, but the .done() method never runs in the jQuery ajax -- additionally the form submits (despite my usage of event.preventDefault();
-- I have also tried return false
but the form still sends). The resulting page is a GET response with my desired quotes (so the query itself is working), but I don't know if I'm formatting my JSON improperly or if I'm handling the callback request from the jQuery ajax incorrectly.
Any ideas? (note, ejs, express, body-parser and mongoose are dependencies in this project)
I've got the following HTML and jQuery to run an AJAX request to a /destroy URL as follows:
My Routes:
app.get('/:id/destroy', function(req, res){
// removes quote by id:
Quote.remove({_id: req.params.id}, function(err){
if (err){
console.log('Remove was unsuccessful...', err);
res.json(err);
};
console.log('DELETED');
// queries for allQuotes:
Quote.find({}).sort({'vote':'desc'}).exec(function(err, allQuotes){
if (err){
console.log(err);
} else {
res.json(allQuotes[0]);
}
})
});
});
My jQuery:
$('form.destroy').submit(function(event){
event.preventDefault();
$.ajax({
url: '/'+$(this).attr('mongoID')+'/destroy',
method: 'GET',
data: $(this).attr('mongoID').serialize(),
})
.done(function(allQuotes){ // this never runs (Why?)
console.log('Showing quotes now again after delete...');
buildAllQuotes(allQuotes); // this never runs but appends response to html data
})
.fail(function(err){
console.log('Error with deletion...', err);
})
.always(function(){
console.log('Done');
})
});
My HTML:
<form action="/'+allQuotes[x]._id+'/destroy" class="destroy" method="GET" mongoID="'+allQuotes[x]._id+'">
<input type="submit" value="Delete">
</form>