0

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

1 Answer 1

1

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");
        }
      }
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.