ajax 使用相同的按钮添加和删除

ajax add and delete with same button

我正在尝试创建一个按钮,单击该按钮时会向该数据库添加 一条记录,再次单击时会删除来自该数据库的这条记录(它是一个 'favourite' 按钮)。

我希望它按如下方式工作;

用户点击'fav'按钮>按钮状态变为成功>添加记录

用户再次单击 'fav' 按钮 > 状态更改为默认值 > 从数据库中删除记录

到目前为止我的代码如下(更新代码感谢@Peter);

books_model.php

class BooksModel
{
 public function checkFav($bookid,$userid)
 {
    $book_id=$_REQUEST['book_id'];
    $user_id=$_SESSION['user_id'];

    $sql = "SELECT * FROM favourite WHERE user_id=? AND book_id=?";
    $query = $this->db->prepare($sql);
    $query->bind_param('ii', $userid,$bookid);
    $query->execute();
    $query->store_result();
    $rows_found = $query->num_rows();
     if(empty($rows_found)) {
        $sql = "INSERT INTO favourite (user_id, book_id)
                VALUES (?, ?)";
        $query = $this->db->prepare($sql);
        $query->bind_param('ii',$userid,$bookid);
        $query->execute();

    } else { 
        $sql = "DELETE FROM favourite WHERE user_id=? AND book_id =?";
        $query = $this->db->prepare($sql);
        $query->bind_param('ii',$userid,$bookid);
        $query->execute();
    }
 }
}

books_controller.php

class Books extends Controller
{
 function checkFav()
 {
    $checkFav_model = $this->loadModel('Books');
 }
}

itemView.php

$(document).ready(function(){
$( "#fav" ).click(function(){  
$( this ).toggleClass( "btn-success" );   
book_id = $(fav).val(); // set the value of the button (book_id)

    $.ajax({
         type: 'POST',
         url: '<?php echo URL; ?>books/checkFav', //location of query
         data: {book_id:book_id}, //taken from value of button

         success: function () { 
             $( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
            }//end success        
        });//end ajax   
    });
});

按钮 html

<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>

目前,当我单击按钮并查看控制台时,我可以看到帖子,但是没有任何内容发送到我的数据库。

感谢任何建议或指导,因为我对 MVC 和 JS 还很陌生。

您可以简单地检查一下: SELECT * FROM favourite WHERE user_id = :user_id AND book_id = :book_id

如果它 returns 有什么,执行 DELETE FROM favourite WHERE user_id = :user_id AND book_id = :book_id

否则插入。

如果你想显示这本书已经被添加为用户的最爱,那么你必须在页面加载时执行另一个调用,为按钮提供一个属性,告诉你和用户它是否已经是最喜欢的.

在最后一种情况下,您不必再进行检查。如果它包含该属性,则只执行 DELETE 查询,否则执行 INSERT

// try to get the attribute of the button
var attr = $(".favoriteButton").attr('data-favorite');
// check the button has the attribute
if (typeof attr !== typeof undefined && attr !== false) {
   //delete query
   $.ajax({
         type: 'POST',
         url: '<?php echo URL; ?>books/deleteFav', //location of query
         data: {book_id:book_id}, //taken from value of button

         success: function () { 
             $( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
            }//end success        
        });//end ajax   
    });
}

类似的东西

使用通用变量:var IsDeleted; var 已添加;然后 IsDeleted = 0;添加=1; (您的书已添加)。删除书籍时再次更改值 IsDeleted = 1;添加=0;当您执行 $( "#fav" ).click(function() 检查这些值并执行您想要的操作(添加、删除)时。

<button class="fvrt" data-item-id="11" data-current-state="0"> Like <button>   // 0 = normal, 1 = liked

$(document).on('click', '.fvrt', function(){

    if($(this).attr('data-current-state') == 0){

         like_item($(this).attr('data-item-id'));   // send ajax request
         $(this).attr('data-current-state', '1');
         $(this).val('Liked');  

    }else{

         dislike_item($(this).attr('data-item-id'));   // send ajax request
         $(this).attr('data-current-state', '0');
         $(this).val('Like');  

    } // checking state 

}); // on clicked
public function checkFav($bookid,$userid)

{

$sql = "SELECT * FROM favourite WHERE user_id=:userid AND book_id=:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
$rows_found = $query->countRows();
 if(empty($rows_found)) {
    $sql = "INSERT INTO favourite (user_id, book_id) VALUES (:userid, :bookid)";
    $query = $this->db->prepare($sql);
    $query->bindParam(':userid', $userid);
    $query->bindParam(':bookid', $bookid);
    $query->execute();

} else { 
    $sql = "DELETE FROM favourite WHERE user_id=:userid AND book_id =:bookid";
    $query = $this->db->prepare($sql);
    $query->bindParam(':userid', $userid);
    $query->bindParam(':bookid', $bookid);
    $query->execute();
}
}
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
checkFav($book_id,$user_id);