我有一个表,其中包含一些数据行,每行都有删除按钮。
如果我用代码实现了sweetalert2,我的表单就不会提交,我需要的是,我只需要在sweetalert确认按钮后删除我的行。这是我的密码;
<tbody>
<?php foreach ($category_details as $category_detail): ?>
<tr>
<td>...</td> <!-- etc -->
<form method="post">
<td>
<input type="hidden" name="delete-id" value="<?php echo $category_detail['id']; ?>">
<button type="submit" name="single-cdelete" class="swa-confirm btn btn-trash-alt">
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</form>
if(isset($_POST['single-cdelete'])){
$delete_id = $_POST['delete-id'];
$delete_image = $_POST['delete-image'];
category_delete($delete_id, $delete_image);
}
function category_delete($delete_id, $delete_image){
global $db;
if(mysqli_query($db, "DELETE FROM categories WHERE id =$delete_id")){
unlink('../assets/images/categories/'.$delete_image);
$_SESSION['success'] = "Category has been deleted successfully";
}else{
$_SESSION['success'] ="Something went wrong, Try again";
}
}
我的SweetAlert代码:
<script>
$(".swa-confirm").on("click", function(e) {
e.preventDefault();
Swal.fire({
title: "Are you Sure ?",
text:"You want to Delete the selected Category",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#cc3f44",
confirmButtonText: "Delete",
closeOnConfirm: true,
html: false
}, function( confirmed ) {
if( confirmed ){
$('.swa-confirm').submit();
}
});
});
</script>
作为@Tangoabc Delta的注释,您只需在表单上使用.submit((事件,因此:
-
首先,给你的表单一个id:
<form method="post" id="swaForm">
-
然后使用这样的脚本:
<script> $(".swa-confirm").on("click", function(e) { e.preventDefault(); Swal.fire({ title: "Are you Sure ?", text:"You want to Delete the selected Category", type: "warning", showCancelButton: true, confirmButtonColor: "#cc3f44", confirmButtonText: "Delete", closeOnConfirm: true, html: false }).then(function() { $('#swaForm').submit(); }) }); </script>
从您的代码中可以明显看出,您已经使用jQuery来执行表单提交。
根据文件,https://api.jquery.com/submit/,方法.submit()
只能在form
上使用。
当用户尝试提交表单时,submit事件会发送到元素。它只能连接到
<form>
元素。。可以通过单击显式、或当某些表单元素具有焦点时按Enter。。。
可以看出,您还依赖于其他一些功能Swal.fire(..)
,因此,您必须执行event.preventDefault()
,否则,表单将可以轻松提交。但可以理解的是,您将需要这部分功能。
因此,为了解决您的问题,您需要将某种标识符添加到表单中,例如class
或id
。因此,与其这样做:
<form method="post">
做,像一样
<form method="post" id="myform">
在代码片段中,使用此标识符调用submit()
:
更新:此外,请注意,sweetalert2
支持promise
,因此,建议使用then
功能承诺,并使用catch
块来跟踪任何错误。
$(".swa-confirm").on("click", function(e) {
e.preventDefault();
Swal.fire({
...
}).then((confirmed) => {
if (confirmed) {
$('#myform').submit(); // << here
}
})
.catch((error) => {
console.log(error)
});
});