'Is there a way to delete an actual target item from the table using PHP, Jquery and Ajax request as i intend herein?
I have a PHP table whose data was streamed-out from the database using the foreach. However, i am trying to create a delete mechanism to it.
Here is my table :- <?php
foreach ($projects as $projectx){
echo '<tr>';
echo '<th>'.$projectx['id'].'</th>';
echo '<td>'.$projectx['user'].'</td>';
echo '<td>'.$projectx['catch_code'].'</td>';
echo '<td>'.$projectx['user_type'].'</td>';
echo '<td>'.$projectx['logs'].'</td>';
echo '<td><a href="view-details" class="btn btn-sm btn-primary view-files" data-id="'.$projectx['id'].'" data-user="'.$projectx['user'].'" data-catchcode="'.$projectx['catch_code'].'" >View</a> <i class="fa fa-trash" id="remove-id" class="btn btn-danger btn-sm remove" aria-hidden="true"></i>
';
}
This is what i have tried so far towards it:-
$('body').on('click', '.fa-trash', e => {
let id = $('td .view-files').data('id');
if(confirm("Do you want to Remove?")){
$.ajax({
url: '/del.php',
type: 'GET',
data:{id:id},
error: function(){
alert("something went wromg");
},
success: function(e){
e.preventDefault;
$("#"+id).parents('tr').remove();
}
});
}
});
Whenever i tried to delete any of the data from the table, the first data on the table is often deleted (not the intended data).
I think i am having a problem integrating/retrieving the font awesome delete class and the actual data through the IDs and classes. Please, how can i go about this?
Solution 1:[1]
(1) Add class="removea" to the td for the delete
(2) Add the id value matching the db record to this td tag
In this way, when the user clicks the td tags of the delete, the system can pass the proper id for deletion by ajax.
So you are good to go using the following:
For the PHP
<?php
echo "<table border=1 id=tblCart>";
foreach ($projects as $projectx){
echo '<tr id=' . $projectx['id'] . '>';
echo '<th>'.$projectx['id'].'</th>';
echo '<td>'.$projectx['user'].'</td>';
echo '<td><a href="view-details" class="btn btn-sm btn-primary view-files" data-id="'.$projectx['id'].'" data-user="'.$projectx['user'].'" data-catchcode="'.$projectx['catch_code'].'" >View</a>
<td class="removea" id=' . $projectx['id'] . '><i class="fa fa-trash" class="btn btn-danger btn-sm remove" aria-hidden="true">Delete</i>
</td>';
}
echo "</table>";
?>
For the JS
<script>
$('.removea').click(function () {
var id = $(this).attr('id');
if(confirm("Do you want to Remove?")){
$.ajax({
url: './del.php',
type: 'GET',
data:{id:id},
success: function(e){
$('#'+id).remove();
}
});
}
});
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
