gpt4 book ai didi

javascript - ajax 使用同一按钮添加和删除

转载 作者:行者123 更新时间:2023-12-02 16:37:18 25 4
gpt4 key购买 nike

我正在尝试创建一个按钮,单击该按钮时将向该数据库添加一条记录,再次单击该按钮时将从该数据库中删除该记录(这是一个“收藏夹” 按钮)。

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

用户点击“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 很陌生。

最佳答案

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

关于javascript - ajax 使用同一按钮添加和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27818780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com