在下面的代码中,我正确地从数据库中获取了所有数据。但接下来我想通过使用动态生成的删除链接来删除特定数据..但是我无法获得特定的ID以便在delete.php页面上发送它。我总是得到未定义的ID,这是我在alert.please帮助我如何获取我的myId变量中的Id发送到下一页。
<script>
$(document).ready(function(){
var myId=$(this).data('Id');
alert(myId);
$(".delete").click(function(){
$.ajax({
type:"Post",
url:"delete.php",
data:{
Id:myId,
},
sucess:function(data){
}
});
});
});
</script>
<?php
$localhost="localhost";
$username="root";
$password="dheeraj";
$dbname="mydatabase";
$con = mysqli_connect('localhost','root','dheeraj','mydatabase');
if(!$con){
echo mysqli_error($con);
}
$action=$_POST['action'];
if($action=='showComment'){
$sql="select * from employee order by Id";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0){
echo "<table border=1px solid red><tr><th>Id</th><th>FirstName</th><th>LastName</th><th>Email</th><th>Contact Number<th>Delete</th></th></tr>";
while($row=mysqli_fetch_array($result)){
echo '<tr><td>'.$row["Id"].'</td><td>'.$row["Fname"].'</td><td>'.$row["Lname"].'</td><td>'.$row["email"].'</td><td>'.$row["contact"].'</td><td><a class="delete" href="?id="'.$row["Id"].'>Delete</a></td></tr>';
}
echo "</table>";
}
}
?>
答案 0 :(得分:0)
您的删除链接元素中没有定义数据属性,请输入:
<a class="delete" href="?id="'.$row["Id"].' data-Id="'.$row["Id"].'">Delete</a>
你的js应该是:
$(document).ready(function(){
// replace document below with top level parent that already existed on page
$(document).on('click', '.delete', function(){
var myId =$(this).data('Id');
alert(myId);
$.ajax({
type:"Post",
url:"delete.php",
data:{
Id:myId,
},
sucess:function(data){
}
});
});
});
答案 1 :(得分:0)
尝试按如下方式重写PHP代码:
if(mysqli_num_rows($result)>0){
echo "<table border=1px solid red><tr><th>Id</th><th>FirstName</th><th>LastName</th><th>Email</th><th>Contact Number<th>Delete</th></th></tr>";
while($row=mysqli_fetch_array($result)){
echo '<tr><td>'.$row["Id"].'</td><td>'.$row["Fname"].'</td><td>'.$row["Lname"].'</td><td>'.$row["email"].'</td><td>'.$row["contact"].'</td><td><a data-id="'.$row["Id"].'" class="delete" href="?id="'.$row["Id"].'>Delete</a></td></tr>';
}
echo "</table>";
和JS一样
<script>
$(document).ready(function(){
$(".delete").click(function(){
var myId=$(this).data('Id');
alert(myId);
$.ajax({
type:"Post",
url:"delete.php",
data:{
Id:myId,
},
sucess:function(data){
}
});
});
});
</script>