1

I've got span inside an LI with a class of removeFile, when clicked, it should remove a file using jQuery $.get and then upon successful deletion, it should fadeout the containing LI. I can't figure out why this is not working, I can get it to alert(data) but not assign to a variable or execute the fadeOut() command.

$('#files').on('click', '.removeFile', function (event) {
    event.preventDefault();
    var fileUrl = $(this).data('file-url');
    if (confirm('Are you sure you want to delete this file?')){
        $.get('process.php', {'remove-file':fileUrl}, function(data){
            if(data=='true'){
                $(this).parent().fadeOut();
            } 
        });
    }
}); 

<li class="file">
<span class="file" data-file-url="http://demo.com/filemanager/files/test.txt" title="test.txt">test.txt</span>
<span class="removeFile" data-file-url="/files/test.txt"></span>
</li>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
drooh
  • 578
  • 4
  • 18
  • 46

2 Answers2

1

Inside ajax callback function this refers to jqXHR object, so you need to define it outside the ajax call as variable or set it the context option.

$('#files').on('click', '.removeFile', function (event) {
    event.preventDefault();
    var $this = $(this);
    var fileUrl = $this.data('file-url');
    if (confirm('Are you sure you want to delete this file?')){
        $.get('process.php', {'remove-file':fileUrl}, function(data){
            if(data=='true'){
                $this.parent().fadeOut();
            } 
        });
    }
}); 
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

this in get() not referencing .removeFile. this refers to xhr object in the callback of get().

$('#files').on('click', '.removeFile', function (event) {
    event.preventDefault();
    var li = $(this).parent(); //added this line
    var fileUrl = $(this).data('file-url');
    if (confirm('Are you sure you want to delete this file?')) {
        $.get('process.php', { 'remove-file': fileUrl }, function (data) {
            if (data == 'true') {
                li.fadeOut(); //changed this line
            }
        });
    }
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55