2013-11-27 39 views
0

我不知道如何獲得jquery .ajax調用的帖子標題。我能夠創建並顯示我的博客文章,現在我正在嘗試添加刪除和編輯功能。我從刪除開始,因爲它顯然是兩者中較容易的。如何從post數組中獲取博客標題到我的functions.js文件中,以便我可以刪除數據庫中的匹配記錄?另外...謝謝!如何使用Ajax和Jquery刪除MySQL記錄?

HTML

<?php 
     include 'scripts/db_connect.php'; 
     include 'scripts/functions.php'; 
     sec_session_start(); 
     $sql = "SELECT * FROM blog"; 
     $result = mysqli_query($mysqli, $sql); 
     while($row = mysqli_fetch_array($result)) 
     { 
      echo'<div class="blog"><h3 class="blog">' . $row['Title'] . "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . "</h3><hr>"; 
      echo'<p class="blog">' . $row['Body'] . '</p><button id="editPost" type="button">Edit</button><button id="deletePost" type="button">Delete</button><button id="commentPost" type="button">Comment</button></div>'; 
     } 

?> 

的functions.php

$function= $_POST['function']; 
$title = $_POST['title']; 
if($function == "deletePost") 
deletePost($title) 
function deletePost($title){ 
$sql = "DELETE FROM blog WHERE Title = '$title';"; 
mysqli_query($mysqli, $sql); 
} 

Functions.js

$(document).ready(function(){ 
    $('#deletePost').on('click', function(){ 
     $.ajax({ 
      url: 'functions.php', 
      data:{function: "deletePost", title: "how do I get the blog title here"} 
      success: function(data){ 
     //confirmation of deletion 
     } 
     }); 
    }); 
}); 

回答

1

既然你期待一個POST請求,你需要指定,同時使該AJAX請求。

$.ajax({ 
    url: 'functions.php', 
    type: 'POST', // specify request method as POST 
    ... 
}); 

應該這樣做。

+0

所以,如果我使用的類型:「POST」那麼我可以搶,我以前的PHP頁面上使用相同的變量? – CodeManiak

+0

當您使用POST時,您將能夠通過AJAX請求訪問傳遞給PHP腳本的所有POST參數。 – techfoobar

1

嘗試這個

<?php 
      include 'scripts/db_connect.php'; 
      include 'scripts/functions.php'; 
      sec_session_start(); 
      $sql = "SELECT * FROM blog"; 
      $result = mysqli_query($mysqli, $sql); 
      while($row = mysqli_fetch_array($result)) 
      { 
       echo'<div class="blog"><h3 class="blog">' . $row['Title'] . "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . "</h3><hr>"; 
       echo'<p class="blog">' . $row['Body'] . '</p><button id="editPost" type="button">Edit</button><a class="deletePost" rel="'. $row['Title'] .'" href="#" >Delete</a><button id="commentPost" type="button">Comment</button></div>'; 
      } 

?> 

$(document).ready(function(){ 
    $(".deletePost").on('click', function(){ 
     $.ajax({ 
      url: 'functions.php', 
      type: 'POST', 
      data:{function: "deletePost", title: $(this).attr('rel')} 
      success: function(data){ 
     //confirmation of deletion 
     } 
     }); 
    }); 
});