2015-10-01 108 views
0

在下面的代码中,我正确地从数据库中获取了所有数据。但接下来我想删除特定的数据通过使用删除链接,这是生成动态beloow ..但我不能得到特定的ID发送到delete.php页面上。我总是得到未定义的ID这是我在alert.please中检查它帮助我如何获得ID在myId变量发送到下一页。如何通过使用jquery和ajax动态生成的表中获取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

在你的删除链接元素没有定义数据属性,把这个:

<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){ 

     } 
     }); 
    }); 
}); 
+0

谢谢先生。其工作正常.. – dheeraj

+0

不客气的队友! –

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> 
相关问题