I am trying to create a button that when clicked will add a record to that database, and when clicked again, will delete this record from that database (it's a 'favourite'
button).
I would like it to work as follows;
User clicks 'fav' button > button state changes to success > record added
User clicks 'fav' button again > state changes to default > record removed from db
So far my code is as follows (updated code thanks to @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
});
});
button html
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
Currently when I click the button and look in the console I can see the post, however nothing is being sent to my db.
Any advice or direction is appreciated as I am quite new to MVC and JS.