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

时间:2015-01-07 11:44:47

标签: javascript php jquery ajax

我正在尝试创建一个按钮,单击该按钮时记录添加到该数据库,再次单击时,将从该数据库中删除此记录(&# 39; sa 'favourite'按钮)。

我希望它的工作原理如下;

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

用户点击'收藏'再次按钮>状态更改为默认值>从db

中删除的记录

到目前为止,我的代码如下(感谢@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都很陌生。

4 个答案:

答案 0 :(得分:1)

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

如果返回某些内容,请执行 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   
    });
}

像这样的东西

答案 1 :(得分:1)

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

答案 2 :(得分:0)

使用通用变量:var IsDeleted; var IsAdded;那么IsDeleted = 0; IsAdded = 1; (你的书已添加)。删除书IsDeleted = 1时再次更改值; IsAdded = 0;当你执行$(“#fav”)。click(function())检查这些值并执行你想要的操作(添加,删除)。

答案 3 :(得分:0)

<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