php - CRUD delete using modal form
问题描述
I am creating a CRUD using PHP extension with PDO, and I want to create a confirmation for registry deletion using Bootstrap modals, but I don't know how I can pass the ID information to the modal to delete, how can I do it?
index.php
<tbody>
<?php
$pdo = DB::connect();
$stmt = $pdo->query("SELECT * FROM people");
while ($row = $stmt->fetch()) {
echo "<tr>";
echo "<th scope='row'>" . $row["id"] . "</th>";
echo "<td>" . $row["first_name"] . "</td>";
echo "<td>" . $row["last_name"] . "</td>";
echo "<td>" . $row["notes"] . "</td>";
if ($row["allowed"]) {
echo "<td>" . "✔" . "</td>";
} else {
echo "<td>" . "✗" . "</td>";
};
echo "<td>";
// modal trigger
echo "<button type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Delete</button>";
echo "</td>";
echo "</tr>";
}
?>
</tbody>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Do you want to delete this registry?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Yes</button>
</div>
</div>
</div>
</div>
解决方案
在此部分中添加您的 ID
echo "<button type='button' class='btn btn-danger' data-toggle='modal' data-target='#exampleModal' onclick='$(".delete_id").val('".$row["id"]."')'>Delete</button>";
然后在模态中添加一个隐藏的输入字段,如下所示:
<input type="hidden" name="delete_id" class="delete_id">
在此函数之前包含 jQuery。您还需要有一个删除文件来传递该变量。请求成功后,您可以重新呈现 HTML。
function deleteRecord() {
var id = $(".delete_id").val();
$.ajax({
url:"/delete.php",
method:"POST",
data:{
id: id,
},
success:function(response) {
},
});
}
在我们存储了 ID 的值之后,我们可以删除它
<button type="submit" class="btn btn-danger" onclick="deleteRecord()">Yes</button>
希望这有帮助
推荐阅读
- python - 如何在 Django Rest Framework ModelViewSets 中添加聚合值
- linux - Linux 如何决定哪个 CPU 内核运行一个进程?
- android - 如何使用 Jetpack Compose 显示日历?
- python - 查找重复项并将 ID 添加为属性 pandas
- flutter - Dart/Flutter 测试是同步执行还是异步执行
- java - 获取 EditText 中的当前光标位置
- r-stars - 带有值的星对象缺少图层
- go - gin gonic 绑定多个参数(查询 + json)
- javascript - 为什么我们需要运行本地服务器来运行纯 html/css/js 应用程序?
- ruby - 如果从散列接收到数据,如何使用 RestClient 发送表单数据?