My code inside of function deletePost is not executing. This is because the contents of $_GET['title']
is empty. I set the value of the title in the ajax using this line postTitle: $(this).siblings("h3.blog").text()
how come the value doesn't make it through the the php script?
index.php
<?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><form name="postForm" method="post" action="process_post.php">
<input type="radio" name="postAction" value="editPost" class="editPost" type="button">Edit</input>
<input type="radio" name="postAction" value="deletePost" class="deletePost" type="button">Delete</input>
<input type="radio" name="postAction" value="commentPost" class="commentPost" type="button">Comment</input></form></div>';
}
?>
What am I doing wrong with $_GET
and the data from ajax?
JavaScript
$('.deletePost').click(function(){
$.ajax({
url:"scripts/post_action.php",
data: {action: "deletePost", postTitle: $(this).siblings("h3.blog").text()},
});
});
post_action.php
<?php
include 'db_connect.php';
include 'functions.php';
if($_GET['action'] == "deletePost")
deletePost($mysqli, $_GET['postTitle']);
function deletePost($mysqli, $title){
$sql = "DELETE FROM blog WHERE Title = '$title'";
mysqli_query($mysqli, $sql);
}
?>
This is because the contents of
$_GET['title']
is empty.
The h3.blog
element is not a sibling of the delete button. It's a sibling of the parent of the delete button (the form
element). To be flexible with your layout, you can use .closest
(traverse up) with .find
(traverse down):
$(this).closest('div.blog').find('h3.blog').text()
You have extra single quote. Try to write:
function deletePost($mysqli, $title){
$sql = "DELETE FROM blog WHERE Title =" . $title;
mysqli_query($mysqli, $sql);
}
Also your code not protected from sql injection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.