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 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题