DaveLar DaveLar - 4 months ago 7
Javascript Question

Remove table rows locally depending on ajax call

I have a table that is updating through reloading the page which I'm trying to handle locally instead. So I render this table below through PHP and then update it through ajax. When I now want to remove rows I want to remove a row when I get a successful response from ajax but the code I have for removal is global and deletes anyway. Is there any way for me to incapsulate my js code in a js function and perhaps call it through an onclick-event?

My table:

<table>
<tr>
<td>1</td>
<td><a class="remove" href='#' onClick="Remove()">Remove</a></td>
</tr>
<tr>
<td>2</td>
<td><a class="remove" href='#'>Remove</a></td>
</tr>
<tr>
<td>3</td>
<td><a class="remove" href='#'>Remove</a></td>
</tr>
</table>


My JS for removal

$(document).on("click", "a.remove", function() {
$(this).closest("tr").remove();
});


And this is where I want to delete the tablerow locally:

function Remove(id) {
$.ajax({
url: "ajax/ajax.php",
type: "POST",
data: {
operation: "remove",
id: id
},
success: function(response){
// This is where I want the deletion to be
},
error: function (response) {
console.log("Something went wrong");
},
});
}


Anyone have an idea on how to redo the js for removal to work in Remove()?

Answer

change your table to

<table>
 <tr>
   <td>1</td>
   <td><a class="remove" data-rowid="1">Remove</a></td>
 </tr>
 <tr>
   <td>2</td>
   <td><a class="remove" data-rowid="2">Remove</a></td>
 </tr>
 <tr>
   <td>3</td>
   <td><a class="remove" data-rowid="3">Remove</a></td>
 </tr>
</table>

the value of data-rowid should be your dynamic item id you want to delete!

and your JS-Code could be:

$(document).on("click", "a.remove", function(event) {
    event.preventDefault();
    var id = $(this).data("rowid");
    var row = $(this).closest("tr");    
    $.ajax({
       url: "ajax/ajax.php",
       type: "POST",
       data: {
          operation: "remove",
          id: id
       },
       success: function(response){
          row.remove();
       },
       error: function (response) {
          console.log("Something went wrong");
       }
    });

});
Comments