public function likepost()
{
if (IsloggedIn()) {
// Check if the request is a POST request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$post_id = $_POST['post_id'];
$user_id = $_SESSION['user_id']; // Assuming the user is logged in and we are storing the user ID in session
// Check if the user already liked this post
if ($this->postModel->hasUserLikedPost($post_id, $user_id)) {
// User has already liked the post, so we need to remove the like
if ($this->postModel->removeLike($post_id, $user_id)) {
// Decrease the like count in the posts table
$this->postModel->decrementLikeCount($post_id);
echo json_encode(['status' => 'unliked', 'likes_count' => $this->postModel->getLikesCount($post_id)]);
}
} else {
// User has not liked the post, so we add the like
if ($this->postModel->addLike($post_id, $user_id)) {
// Increase the like count in the posts table
$this->postModel->incrementLikeCount($post_id);
echo json_encode(['status' => 'liked', 'likes_count' => $this->postModel->getLikesCount($post_id)]);
}
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'User not logged in']);
}
}
Ниже приведен код моей модели:
public function hasUserLikedPost($user_id, $post_id) {
echo $this->db->query('SELECT * FROM post_likes WHERE user_id = :user_id AND post_id = :post_id');
$this->db->bind(':user_id', $user_id);
$this->db->bind(':post_id', $post_id);
$row = $this->db->single();
return $row ? true : false;
}
public function addLike($post_id, $user_id) {
$this->db->query('INSERT INTO post_likes (post_id, user_id) VALUES (:post_id, :user_id)');
$this->db->bind(':post_id', $post_id);
$this->db->bind(':user_id', $user_id);
return $this->db->execute();
}
public function removeLike($post_id, $user_id) {
$this->db->query('DELETE FROM post_likes WHERE post_id = :post_id AND user_id = :user_id');
$this->db->bind(':post_id', $post_id);
$this->db->bind(':user_id', $user_id);
return $this->db->execute();
}
public function incrementLikeCount($post_id) {
$this->db->query('UPDATE posts SET likes_count = likes_count + 1 WHERE id = :post_id');
$this->db->bind(':post_id', $post_id);
return $this->db->execute();
}
public function decrementLikeCount($post_id) {
$this->db->query('UPDATE posts SET likes_count = likes_count - 1 WHERE id = :post_id');
$this->db->bind(':post_id', $post_id);
return $this->db->execute();
}
public function getLikesCount($post_id) {
$this->db->query('SELECT likes_count FROM posts WHERE id = :post_id');
$this->db->bind(':post_id', $post_id);
return $this->db->single()->likes_count;
}
Вот мой код просмотра:
Ниже приведен мой запрос AJAX, написанный в моем файле main.js.
document.addEventListener("DOMContentLoaded", function () {
let btn = document.getElementById("upvote");
if (!btn) {
console.error('Element with ID "upvote" not found');
return;
}
let disp = document.getElementById("display");
let post_id = btn.getAttribute("data-post-id");
btn.onclick = function () {
// Create an AJAX request to send the post_id to PHP
let xhr = new XMLHttpRequest();
xhr.open("POST", "/posts/likepost", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Handle the response from PHP
let response = JSON.parse(xhr.responseText);
if (response.status === 'liked') {
disp.innerHTML = response.likes_count; // Update the like count
} else if (response.status === 'unliked') {
disp.innerHTML = response.likes_count; // Update the like count
}
}
};
// Send the post_id as part of the request
xhr.send("post_id=" + post_id);
}
});
Всякий раз, когда я пытаюсь запустить это, я получаю следующую ошибку в консоли:
[img]https://i. sstatic.net/LQIQlRdr.png[/img]

Что касается этой ошибки, она показывает ошибку в другом моем методе, который работает нормально, я также вставляю ее сюда для справки:
public function show($id)
{
$post = $this->postModel->getPostById($id);
$user = $this->userModel->getUserById($post->userid);
$data = [
'post' => $post,
'user' => $user,
];
$this->view('posts/show',$data);
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... hod-in-php
Мобильная версия