簡體   English   中英

Ajax刪除功能不起作用

[英]Ajax delete function not working

我正在嘗試使用jQuery Ajax函數刪除MySQL數據庫中的行。 當我單擊帖子的“刪除帖子”鏈接時,我希望它觸發一個onClick事件,該事件將運行刪除行功能。

到目前為止,這是我的代碼:

首先顯示帶有鏈接的帖子以刪除每一個。

foreach($postarray AS $value){
echo '<div class="item">'.$value['post_title'].'  , <a href="#" class="delete_link" value="'. $value['post_id'] .'">Delete Post</a></div>';

}

然后是Jquery:

$(document).ready(function(){
$(".delete_post").click(function(){
        var id = $(this).attr("value");

        function deletePost(id){
            $.ajax({
                type: "POST",
                url: "delete_post.php",
                data: {id: id},
                success: function(data){
                    alert("Post deleted");
                }
            })
        }
    });

});

delete.php代碼:

//Start the session
session_start();
require_once('func/auth.class.php');
require_once('func/functions.php');
require_once('func/db.class.php');

// Check if user is logged in
if(!$_SESSION['is_admin'] || empty($_POST['id'])){
    header("Location: index.php");
}

$post_id = $_POST['id'];
delete_post($post_id);

delete_post()函數:

function delete_post($post_id){
        global $dbh;

        $stmt = $dbh->prepare("DELETE FROM mjbox_posts WHERE post_id = ?");
        $stmt->bindValue(1, $post_id, PDO::PARAM_INT);
        $stmt->execute();

        if($stmt->rowCount() != 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }

當前,此方法不是從數據庫中刪除帖子,我也不知道為什么。

正如jcho360在評論中提到的那樣,在綁定到click事件時,css類有一個錯誤。

修復后,它將仍然無法使用。 當觸發click事件時,您將聲明一個刪除帖子的函數,但您沒有在調用它。 一種解決方法是將其更改為以下內容:

$(document).ready(function(){
    $(".delete_link").click(function(){
        var id = $(this).attr("value");

        $.ajax({
            type: "POST",
            url: "delete_post.php",
            data: {id: id},
            success: function(data){
                alert("Post deleted");
            }
        });
    });
});

這樣,在觸發click事件時,您實際上是在發出請求。

更進一步,我只是注意到在ajax調用中,您正在請求“ delete_post.php”,但是您提到您的php文件稱為delete.php。 這也需要解決。

您可以在瀏覽器中使用檢查器來查看單擊鏈接時發生的情況。 它是否發出請求? id參數設置正確嗎? 依此類推。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM