How would you delete a row from a table using AJAX based on this code?
Here's the PHP code I'm working with:
foreach ($results as $result) {
echo "<tr><td>".$result['first_name']."</td><td>".$result['last_name']."</td><td><button class=\"btn btn-sm btn-danger delete_class\" id=\"".$result['id']."\" >DELETE</button></td></tr>";
}
As you can see, the button has an id paired with it.
Here's my jquery/AJAX code to delete the file from the database:
<script>
var $tr = $(this).attr('parentElement');
$('.delete_class').click(function(){
var del_id= $('.delete_class').attr('id');
$.ajax({
url:"delete_page.php?delete_id="+del_id,
cache:false,
success:function(result){
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
});
}
});
});
</script>
There is also a PHP file that goes into the database and deletes the data, which works fine.
In the javascript code above ^ the variable being set at the top "$tr" is saying the 'parentAttribute' is the "td" not the "tr", how would I go up two parent attributes?
What can I change my "success:function(result){ }" to to make the row immediately disappear, because,
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
}
this code ^ isn't working.
Change your current jquery
code as shown below:
<script>
$('.delete_class').click(function(){
var tr = $(this).closest('tr'),
del_id = $(this).attr('id');
$.ajax({
url: "delete_page.php?delete_id="+ del_id,
cache: false,
success:function(result){
tr.fadeOut(1000, function(){
$(this).remove();
});
}
});
});
</script>
The closest
method returns the first ancestor of the selected element. https://api.jquery.com/closest/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments