正如标题所示,我创建了按钮并将其定位为表格中的最后一列。该表从MySQL中提取并正确显示所有值。新条目还有另一种形式,效果很好。
我已经通过适当的验证工具在线运行我的代码,并且它们通过而没有错误。所以,我想知道我的问题在于它没有传递要删除的行的值。或者真的,总体上是不正确的,或者是否有更好的方法来编码。我是PHP的新手,特别是AJAX,所以我想知道我在哪里出错?在此先感谢,如果需要更多信息,那么我很乐意遵守。
以下是HTML和PHP的代码:
<?php
@$db = new mysqli('localhost', 'root', 'pwdpwd', 'pet_shop');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$groomings = 'SELECT * from grooming';
$result = $db->query($groomings);
}
?>
<table align="center" border="1">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Phone</th>
<th>Email</th>
<th>Pet Type</th>
<th>Breed</th>
<th>Pet Name</th>
<th>Neutered/Spayed</th>
<th>Pet Age</th>
<th>Edit/Delete</th>
</tr>
<?php
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>' . $row['GroomingID'] . '</td>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Address'] . '</td>';
echo '<td>' . $row['City'] . '</td>';
echo '<td>' . $row['State'] . '</td>';
echo '<td>' . $row['Zip'] . '</td>';
echo '<td>' . $row['PhoneNumber'] . '</td>';
echo '<td>' . $row['Email'] . '</td>';
echo '<td>' . $row['PetType'] . '</td>';
echo '<td>' . $row['Breed'] . '</td>';
echo '<td>' . $row['PetName'] . '</td>';
echo '<td>' . $row['NeuteredOrSpayed'] . '</td>';
echo '<td>' . $row['PetAge'] . '</td>';
echo '<td>' . '<button action="delete.php" class="del_btn" rel="'.$row["GroomingID"].'">' . 'Delete' . '</button>' . '</td>';
echo '</tr>';
}
?>
和Jquery / Ajax:
<script>
$(document).ready(function(){
$('.del_btn').click(function(){
var del_id = $(this).attr('rel');
$.post('delete.php', {delete_id:del_id}, function(data) {
if(data == 'true') {
$('#'+del_id).remove();
} else {
alert('Could not delete!');
}
});
});
});
</script>
</table>
<?php
$result->free();
$db->close();
?>
这是运行查询的delete.php文件:
<?php
function dbString($string)
{
$string=trim($string);
if (get_magic_quotes_gpc())
{
return $string;
}
else
{
return addslashes($string);
}
}
@$db = new mysqli('localhost', 'root', 'pwdpwd', 'pet_shop');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
if(isset($_POST['delete_id']) && !empty($_POST['delete_id']))
{
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM grooming WHERE GroomingID=".$delete_id);
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body
onload="document.createElement('form').submit.call(document.getElementById('newEntry'))">
<form action="admin.php" id="newEntry">
<input type="submit" value="confirm">
</form>
</body>
答案 0 :(得分:0)
在您的实际代码中,您尝试删除不存在的HTML元素
$('#'+del_id).remove();
我在代码中的任何地方都看不到具有此类ID的元素。尝试这样做:
<?php
while ($row = $result->fetch_assoc())
{
echo '<tr id="'.$row['GroomingID'].'">'; // <-- HERE
echo '<td>' . $row['GroomingID'] . '</td>';
此外,您应将所有javascript代码放在html页面的<head>
部分,而不是<body>