so i have a function on my website where a user can favourite a post, but when i click the button it returns error “Post ID not provided” (see below) how can i fix this?
php function:
public function toggleLike($post_id){
$is_like = $this->isLike($post_id);
if($is_like) {
$query = "DELETE FROM user_like WHERE like_id = :like_id";
$stmt = $this->Conn->prepare($query);
$stmt->execute([
"like_id" => $is_like['like_id']
]);
return false;
}else{
$query = "INSERT INTO user_like (profile_id, post_id) VALUES
(:profile_id, :post_id)";
$stmt = $this->Conn->prepare($query);
return $stmt->execute(array(
"profile_id" => $_SESSION['user_data']['profile_id'],
"post_id" => $post_id
));
return true;
}
}
and my toggle like Ajax is as follows:
<?php
session_start();
require_once(__DIR__.'/../includes/autoloader.php');
require_once(__DIR__.'/../includes/database.php');
if($_SESSION['user_data']){
$post_id = (int) $_POST['post_id'];
if($post_id) {
$userlike = new userLike($Conn);
$toggle = $userlike->toggleLike($_POST['post_id']);
if($toggle) {
echo json_encode(array(
"success" => true,
"reason" => "Post was added to users likes."
));
}else{
echo json_encode(array(
"success" => true,
"reason" => "Post was removed from users likes."
));
}
}else{
echo json_encode(array(
"success" => false,
"reason" => "Post ID not provided."
));
}
}else{
echo json_encode(array(
"success" => false,
"reason" => "User not logged in."
));
}
I am expecting it to insert a like into the database
The toggle function is a javascript file and is as follows:
$(function() {
$('body').on('click', '#addFav', function(e) {
var post_id = $(this).data('postid');
$.ajax({
method: "POST",
url: "./ajax/togglelike.php",
dataType: 'json',
data: {
post_id: post_id
}
})
.done(function(rtnData) {
console.log(rtnData);
$('#addFav').text('Removed From Favorites').attr('id', 'removeFav');
});
});
$('body').on('click', '#removeFav', function(e) {
var post_id = $(this).data('postid');
$.ajax({
method: "POST",
url: "./ajax/togglelike.php",
dataType: 'json',
data: {
post_id: post_id
}
})
.done(function(rtnData) {
console.log(rtnData);
$('#removeFav').text('Add to Favorites').attr('id', 'addFav');
});
});
});