Reputation: 13
I made a simple PHP blog system. Under the Add Post page user can give a title and body text. The posts are on the Posts page, where the user can delete the posts.
My problem is: Only the first post can be deleted. The others not.
Here is my code for show the posts:
<?php
$database->query('SELECT * FROM posts');
$rows = $database->resultSet();
?>
<div class="container">
<?php foreach ($rows as $row) : ?>
<h2><?php echo $row['title']; ?></h2>
<p><?php echo $row['body']; ?></p>
<small><?php echo $row['create_date'] ?></small>
<form method="post">
<input id="deleteid" type="hidden" name="delete_id" value="<?php echo
$row['id'] ?>">
<input id="delete_button" class="btn btn-primary" type="submit"
name="delete" value="Delete">
</form>
<?php endforeach; ?>
<br><br>
</div>
And this is my AJAX code:
$("#delete_button").click(function () {
$.ajax({
type: "POST",
url: "?action=delete",
data: "delete_id=" + $("#deleteid").val(),
success: function (result) {
if (result == 1) {
//window.location.assign("views/posts.php");
} else {
alert("Error");
}
}
});
});
Upvotes: 0
Views: 220
Reputation: 2466
You cannot use same id for multiple input/div or any other HTML tags. Please change id="deleteid" to class="deleteid" and also change in your click event. So your this line will change to -
<input class="deleteid" type="hidden" data-deleteid="<?php echo
$row['id'] ?>" name="delete_id" value="<?php echo $row['id'] ?>">
And you ajax code will change to -
$(".delete_button").click(function () {
var deleteid = $(this).data('deleteid');
$.ajax({
type: "POST",
url: "?action=delete",
data: "delete_id=" + deleteid ,
success: function (result) {
if (result == 1) {
//window.location.assign("views/posts.php");
} else {
alert("Error");
}
}
});
});
Upvotes: 1