-1

I'm working on an application by using jquery ajax mathod and trying to delete table row by clicking on delete button. The backend part of php is fine but what i'm trying to apply is hide or fadeOut() jquery method on click event but unable to get the result. See following code:

$('.deletePageBtn').on('click', function(e) {
  e.preventDefault();

  if (confirm('Do you really want to delete this page?')) {
    var pageId = $(this).data("pageid");
    $.ajax({
      url: "<?= base_url('admin/pagemanagerSavePage')?>",
      type: 'POST',
      data: {
        action: "delete-page",
        pageId: pageId
      },
      success: function(data) {
        if (data == 'success') {
          $(this).parent().parent().remove();
        }
        console.log(data);
      },
      error: function(data) {
        console.log(data);
      }
    });
  };
});
<tr id="rowId_26" class="rowData odd" role="row">
  <td class="text-center sorting_1">3</td>
  <td class="bg-success text-light text-center">
    <i class="fas fa-eye"></i>
  </td>
  <td>
    Pawan Mall - Internet Geek 123
    <div class="btn-group float-right">
      <a href="#" class="btn btn-sm btn-primary" target="_blank">
        <i class="fas fa-eye"></i> View Page
      </a>
      <a href="" id="editPage" class="btn btn-sm btn-warning">
        <i class="fas fa-edit"></i> Edit Page
      </a>
      <a href="" data-pageid="26" class="btn btn-sm btn-danger deletePageBtn">
        <i class="fas fa-trash"></i> Delete Page
      </a>
    </div>
  </td>
</tr>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Code GuruDev
  • 348
  • 3
  • 11

1 Answers1

2

The issue here is inside ajax success:

success: function(data) {
   if (data == 'success') {
      $(this).parent().parent().remove();
   }
   console.log(data);
},

this refers to the jqXHR object of the Ajax call. Its not same $('.deletePageBtn') element anymore. To make this work you can cache this at start inside click event like:

var $this = $(this);

and then use it inside success like:

success: function(data) {
   if (data == 'success') {
      $this.parent().parent().remove();
   }
   console.log(data);
},

or, better:

success: function(data) {
   if (data == 'success') {
      $this.closest('tr').remove();
   }
   console.log(data);
},
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Shouldn't this `$this.parent().parent().remove();` be `$this.parent().parent().parent().remove();` since the clicked element is a descendant of `
    `, ``, ``? Of course, as you said, the better option is `closest('tr')`.
    – Rob Moll Apr 04 '20 at 15:50