I’ve been working on making an ajax save to favorite function for my project and I been ending up with this code. Please bear in mind im a noob and I’m sure it could look alot better to advice in addition to the problem is very much appreaciated.
The problem appears when I do a second click to remove it, I get issues with the php hander file. I will post the content of both
$(document).on('click', '.button6', function() {
const tankID = <?php echo $tankID; ?>;
const userID = <?php echo $userID; ?>;
const favX = <?php echo $favX+1; ?>;
var fx = document.getElementById('dataTxt');
var favorite = fx.getAttribute('data-id');
console.log("Favorite: " + favorite + "!");
if (favorite == 0) {
$.post('tanks_favorite_ajax.php', { tankID: tankID, userID: userID, favorite: favorite }, function() {
document.getElementById("icon").src="https://www.fsd.com/icons/heartarrow.png";
document.getElementById("dataTxt").innerHTML = "Favorited by "+ favX +" driver(s)";
favorite = !favorite;
var d = document.getElementById("dataTxt");
d.setAttribute('data-id' , favorite);
console.log("1.Favorite is now: " + favorite + "!");
});
} else {
$.post('tanks_favorite_ajax.php', { tankID: tankID, userID: userID, favorite: favorite }, function() {
document.getElementById("icon").src="https://www.fsd.com/icons/arrow.png";
document.getElementById("dataTxt").innerHTML = "Add to Favorites";
favorite = !favorite;
var d = document.getElementById("dataTxt");
d.setAttribute('data-id' , favorite);
console.log("2.Favorite is now " + favorite + "!");
});
}
});
<?php
include('connection.php');
include('functions.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tankID'])) {
$tankID = (int) $_POST['tankID'];
$userID = (int) $_POST['userID'];
$favorite = (int) $_POST['favorite'];
try {
if ($favorite == 0) {
$stmt=$pdo->Prepare("INSERT INTO favorites (tankID, userID)
VALUES (:tankID, :userID)");
$stmt->execute(array(
':tankID' => $tankID,
':userID' => $userID
));
//Add credits
addCredit($userID, $tankID, FAVORITE, 'favorite');
}
elseif ($favorite == 1) {
$stmt=$pdo->Prepare('DELETE FROM favorites WHERE tankID=:tankID AND userID=:userID');
$query->execute(array(
':tankID' => $tankID,
':userID' => $userID
));
}
} catch (PDOException $e) {
echo 'error: ' . $e->getMessage();
}
} else {
echo 'Invalid request';
}
?>