0

I'm trying to make a to-do list type thing. Here, I want the new goal to be saved to the database, and then for only the div with the relevant list to refresh, showing the list with the new goal added.

The database updates fine, the new html with the new list item is returned just fine, but .replaceWith() doesn't seem to work. Nothing happens.

It works outside of that function, but not inside of it, and I'm not sure why.

$('.addGoal').submit(function(event){
    var listid = $(this).attr('id');
    var desc = $(this).children('.goalinput').val();

    event.preventDefault();

    if(desc == "") {
        console.log("empty!");
        return;
    }

    var posting = $.post("updatedata.php", { what :'addgoal', id: listid, data: desc});
    posting.done(function(data){
            console.log("saved!" + data); //this works, the updated html is being returned
            $(this).closest('#goallist').replaceWith("Returned data goes here"); //this works outside of this function but not inside of it. 
        });
    });
Cactuar
  • 3
  • 2

2 Answers2

2

this doesn't automatically keep its value in the callback function. You need to bind a closure variable:

$('.addGoal').submit(function(event){
    var listid = $(this).attr('id');
    var desc = $(this).children('.goalinput').val();

    event.preventDefault();

    if(desc == "") {
        console.log("empty!");
        return;
    }

    var that = this; // Closure variable
    var posting = $.post("updatedata.php", { what :'addgoal', id: listid, data: desc});
    posting.done(function(data){
        console.log("saved!" + data);
        $(that).closest('#goallist').replaceWith("Returned data goes here");
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Please see

But since IDs are supposed to be unique in an HTML document anyway, you can replace $(this).closest('#goallist') with $('#goallist') and completely ignore this.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143