weixin_33695450 2016-08-29 12:57 采纳率: 0%
浏览 21

使用$ .ajax删除帖子

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID

<button type="button" onclick="submitdata();">Delete</button>

When click this button then following $.ajax process running.

<script>
    var post_id="<?php echo $userIdRow['post_id']; ?>";
    var datastring='post_id='+post_id;
    function submitdata() {
        $.ajax({
            type:"POST",
            url:"delete.php",
            data:datastring,
            cache:false,
            success:function(html) {
                alert(html);
            }
        });
        return false;
    }
</script>

And delete.php is

<?php

// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
    $post_id = $_GET['post_id'];

// delete record from database
    if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
        $userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
        $userPostsQuery->execute();
        $userPostsQuery->close();
        echo "Deleted success";
    } else {
        echo "ERROR: could not prepare SQL statement.";
    }

}
?>

This code not working post not deleted. Please how do I do?

  • 写回答

4条回答 默认 最新

  • weixin_33716941 2016-08-29 13:00
    关注

    The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request

    Change:

    type:"POST",
    url:"delete.php",
    data:datastring,
    

    to

    type:"DELETE",
    url:"delete.php?" + datastring,
    

    in PHP

    if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
        $id = $_REQUEST["post_id"];
       // perform delete
    }
    

    DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog