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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动