2013-04-22 68 views
0

我正在嘗試使用jQuery Ajax函數刪除MySQL數據庫中的一行。 當我點擊帖子「刪除帖子」鏈接時,我想讓它觸發一個onClick事件,它將運行刪除行功能。Ajax刪除功能不起作用

這是到目前爲止我的代碼:

首先與鏈接刪除每一個顯示的帖子。

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; 
     } 
    } 

目前這種方法並不DELET從數據庫中的帖子,我不知道爲什麼。

+1

我沒有看到類'「delete_post」' – jcho360 2013-04-22 16:04:54

+0

@ jcho360你,我只看到「delete_link」級 – 2013-04-22 16:06:15

+1

我的不好,忘了更改堆棧 – crm 2013-04-22 16:06:27

回答

1

由於jcho360在評論中提到您在綁定到click事件時在css類中有錯誤。

一旦你解決了它,它仍然無法工作。當點擊事件被觸發時,你正在聲明一個刪除帖子的函數,但你沒有調用它。其中一個補丁可以將其更改爲以下:

$(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"); 
      } 
     }); 
    }); 
}); 

這樣你實際上是在進行請求時點擊事件。

更多我剛剛注意到,在ajax調用中,你要求「delete_post.php」,但你提到你的php文件被稱爲delete.php。這也需要修復。

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