[英]How do I delete a MySQL record using Ajax and Jquery?
我不知道如何將帖子標題放入jquery .ajax調用中。 我能夠創建和顯示我的博客帖子,現在我正在嘗試添加刪除和編輯功能。 我從刪除開始,因為它顯然更容易。 如何將post數組中的博客標題導入到我的functions.js文件中,以便刪除數據庫中的匹配記錄? 還有...謝謝!
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
}
});
});
});
由於您需要POST請求,因此您需要在發出AJAX請求時指定它。
$.ajax({
url: 'functions.php',
type: 'POST', // specify request method as POST
...
});
應該這樣做。
嘗試這個
<?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
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.