doukanxi4246 2017-09-04 15:16
浏览 49
已采纳

PHP和AJAX删除仅适用于第一行

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条回答 默认 最新

  • dongtan7639 2017-09-04 15:25
    关注

    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");
            }
          }
        });
      });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料