【问题标题】:how to delete from database row selected with jquery如何从使用 jquery 选择的数据库行中删除
【发布时间】:2015-01-27 23:03:21
【问题描述】:

我有以下代码:

文件讲师.php:

$(document).ready(function(){
             $(".use-address").click(function() {
             var $row = $(this).closest("tr");    // Find the row
             var names = $row.find(".name").text(); // Find the name
             var surname = $row.find(".surname").text(); // Find the surname                

                $.ajax({
                    type: "POST",
                    url: "delete_lecturer.php",
                    data:{ x: names, y: surname}
                });

             });

        });

文件 delete_lecturer.php:

<?php

ob_start(); //eliminates buffer collisions
    require_once('connect_db.php'); 
    if (!empty($_POST['x'])){   $name = $_POST['x']; }
    if (!empty($_POST['y'])){   $surname = $_POST['y']; }
    $result = pg_query(connect(), "delete from lecturer where name='$name' and surname='$surname'");    
    echo "did it";
    //dump the result object
    var_dump($result);
    // Closing connection

    //reloading the page
    header("location: lecturer.php?fail=2");
?>

文件 connect_db.php 有效(我已经用其他需要它的文件对其进行了测试)。我正在尝试从表中获取名称和姓氏,将其传递给 delete_lecturer.php 文件并从数据库中删除与我的选择匹配的行。 jquery 代码中的姓名和姓氏存储正确(我也测试过)。

但代码仍然不起作用。 任何想法有什么问题或如何解决? 顺便说一句,我使用 postgresql 作为数据库。

【问题讨论】:

  • 您的控制台是否在执行该功能后向您显示某种错误?或者在ajax执行后写一个success(msg)和fail(msg)之类的代码,不要做"header"
  • 我会试试你的建议,谢谢。但现在它不会显示任何错误。
  • 您也可以尝试,在发送数据“names”和“surname”之前对这两个变量执行console.log(),以检查它们是否包含某些内容
  • 我删除了标题行并回显了 $name。什么都没发生。还添加了警报(姓名+姓氏);在 jquery 中获取数据后。它们在警告框中正确打印。
  • 您受制于SQL injection 改用pg_query_params() -- 重定向(Location 标头)ajax 调用对我来说没有太大意义 -- 你确定 jquery 发送你的 ajax 请求吗urlencoded(不是作为 json 字符串)?

标签: php jquery postgresql


【解决方案1】:

你可以这样做:

           $.ajax({  type: "POST",  
                url: "delete_lecturer.php",
                data: { x: names, y: surname}
            })

            .done(function( msg ) {
                msg = $.trim(msg);
                // Use alert or console.log()
                alert(msg);
                console.log(msg);
            })
            .fail(function( msg ) {
                // Use alert or console.log()
                alert(msg);
                console.log(msg);
            });

使用该代码,您可以检查您的代码在哪里出错,因为它似乎没有任何问题

【讨论】:

  • 我还没有解决这个问题,但它似乎是一个外键问题。生病处理它。感谢您的建议。我还不能评价答案 - 但你的答案可能刚刚救了我。
  • 好的,如果你能帮助你解决这个问题,请尽快评价我的回答,如果你想知道你是如何解决问题的,请在最后发表评论
  • 我当然会。目前,由于我正在删除的行包含在其他两个表中引用的键,因此它不会让我使用该查询将其删除。你建议的日志向我表明了这一点。我真的没有想过。
  • 如果你不能给答案评分,至少你可以把它标记为完成;点击向下箭头下的“检查按钮”
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多