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.

    评论

报告相同问题?