I want to make the delete button, once clicked, it will popup a modal (sweetalert). I have a few records that I wanted to test deleting it. But whenever I clicked on "
Delete", it will always redirect to the
delete.php page without opening the modal first. The table is using
foreach
loop to display records from database.
Code:
<?php
if($result)
{foreach($result as $row) {
?>
<tr>
<td class="tb-col" style="width: 15%;">
<?php echo $row['admin_id']; ?></td>
<td class="tb-col">
<div class="media-group">
<div class="media-text">
<a href="#" class="title">
<?php echo $row['admin_fName']." ".
$row['admin_lName']; ?></a>
<?php echo $row['admin_email']; ?>
</div>
</div>
</td>
<td class="tb-col"><?php echo $row['admin_username']; ?></td>
<td class="tb-col">
<?php
$registrationDate = $row['registration_date'];
$formattedDate =
date('jS F Y', strtotime($registrationDate));
echo $formattedDate;
?>
</td>
<td class="tb-col tb-col-end" style="width: 15%;">
<a href ="delete.php?id=<?= $row['admin_id']; ?>"
id="btn-del" class="btn btn-soft btn-outline-danger">Delete
</a>
</td>
</tr>
<?php
}
}
?>
The JavaScript is:
<!-- JavaScript -->
<script src="./assets/js/bundle.js"></script>
<script src="./assets/js/scripts.js"></script>
<script src="./assets/js/data-tables/data-tables.js">
</script>
<script src="./assets/js/sweetalert/sweetalert2.all.min.js"></script>
<script src="./assets/js/sweetalert/jquery-3.7.1.min.js">
</script>
<script>
$(document).ready(function() {
$('#btn-del').on('click', function (e) {
e.preventDefault();
const href = $(this).attr('href');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#2dc58c',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = href;
}
});
});
});
</script>
What I have tried:
The modal itself works fine. I have tested it outside of the table and the
foreach
loop. If it's just one button, it will pop up the modal. The only issue is that, this isn't working on
foreach
loop table I have created.
Since everytime I click on
Delete and it keeps redirecting me to
delete.php, my guess is that the button itself wasn't even captured in the JavaScript at all.
Code:
<div class="nk-block-head-content">
<ul class="d-flex">
<li class="d-none d-md-block">
<a href="./html/delete.php" id="btn-del"
class="btn btn-soft btn-primary"><span>Delete</span></a>
</li>
</ul>
</div>