douhao9203 2018-08-03 06:59
浏览 170
已采纳

使用AJAX和PHP从表中删除数据

Can you explain me where is the problem? Because I lost all my hope for this... Insert and load work but delete not... When I remove if statement from delete, it says id is undefined index. But why it should be undefined when I define it in var id = $(this).data("id3"); I think the problem will be somewhere in select.php with a button. I have lack of experience with AJAX so I ask you for help with this problem.

Thank you for response. (sorry for the language)

Index.php

$('.btn_delete').on('click', function()
{
    var id = $(this).data("id3");

    if (confirm('Naozaj zmazat ?')) {
        $.ajax({
            url: 'delete.php',
            type: 'POST',
            data: {delete: 1, id: id},
            success: function(data)
            {
                alert(data);
                fetch_data();
            }
        });
    }
});

delete.php

if (isset($_POST['delete'])) {
    include("db.php");

    $id = mysqli_real_escape_string($conn, $_POST['id']);    
    $sql = "DELETE FROM suciastka WHERE id_suciastka = '".$id."'";

    if (mysqli_query($conn, $sql)) {
        echo "Deleted";
    }
}

And here is my select.php

include("db.php");

$output = "";
$sql = "SELECT * FROM suciastka";
$result = mysqli_query($conn, $sql);

$output .= "
        <div class='table-responsive'>
            <table class='table table-bordered'>
                <tr>
                    <th>ID</th>
                    <th>NAME</th>
                    <th>NUMBER</th>
                    <th>PLACE</th>
                    <th>DESCR</th>
                    <th>ACTION</th>
                </tr>";
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_array($result)) 
    {   
        $output .= "
            <tr>
                <td>".$row['id_suciastka']."</td>
                <td>".$row['name_suciastka']."</td>
                <td>".$row['number_suciastka']."</td>
                <td>".$row['place_suciastka']."</td>
                <td>".$row['descr_suciastka']."</td>
                <td><button type='button' name='delete_btn' data-id3='".$row['id_suciastka']."' class='btn btn-danger btn_delete'>Delete</button></td>
            </tr>";
    }

}

$output .= "</table>
        </div>";

echo $output;
  • 写回答

4条回答 默认 最新

  • douqie1816 2018-08-03 07:17
    关注

    I think your button is not in the DOM You can try:

    $(document).on('click', '.btn_delete', function() {})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?