skip to Main Content

my click on span sends an ajax request and delete clicked todo from database. but in the dom it is not removed until i refresh my page.

my index.html

<ul class="list">
</ul>

in my network tab it sends two xhr requests which i was not mentioned in code.

error image

app.js

$(".list").on("click","span",function(e) {
  e.stopPropagation();
  deleteTodo($(this).parent());
});
function deleteTodo(el) {
  let todoId = el.data("id"), deleteURL = "api/todos/" + todoId;

  $.ajax({
    method: "DELETE",
    url: deleteURL,
  }).then(function(data) {
    el.remove();
  }).catch(function(err) {
    console.log(err);
  });
}

2

Answers


  1. Chosen as BEST ANSWER

    error image

    The above picture shows that the problem was on the server side. In my node backend API's Router.js file has a code that redirects it to the /api/todos url after deleting a todo. this error caused my app.js to reject the promise. so i was not able to update the DOM.

    error causing code

    router.delete("/:todoId", function(req, res){
        db.Todo.findOneAndDelete(req.params.todoId)
        .then(function(){
            res.redirect("/api/todos");
        })
        .catch(function(err){
            res.send(err);
        })
    

    edited code

    router.delete("/:todoId", function(req, res){
        db.Todo.findOneAndDelete(req.params.todoId)
        .then(function(){
            res.json({message: 'We deleted it!'});
        })
        .catch(function(err){
            res.send(err);
        })
    

  2. To remove the element after deleting it from the database, get the el parent element, then make the parent remove it

    function deleteTodo(el) { let todoId = el.data("id"),    deleteURL = "api/todos/" + todoId; $.ajax({ method: "DELETE", url: deleteURL, }).then(function(data) { 
    var elparent = $('el parent element')[0];
    elparent.removeChild(el); }).catch(function(err) { console.log(err); }); }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search