I made like / dislike buttons in a news feed (like Facebook). I want to change the database when someone clicks on either one of those buttons using PHP. I first made the two buttons in a form but then the PHP would be run on a different page and reload the first page causing you to go back to the top of the news feed (which of course shouldn't happen). Then I tried Javascript, but I needed to pass the id of the post from Javascript to PHP. I tried doing this with Cookies:
document.cookie= and $_COOKIE[]
function like(id) {
document.cookie="lid="+id;
<?php query("INSERT INTO `likes`(`uid`, `pid`) VALUES (".$_SESSION['id'] . ",".$_COOKIE['lid'].")"); ?>
}
function dislike(id) {
document.cookie="lid="+id;
<?php query("DELETE FROM `likes` WHERE uid=".$_SESSION['id'] . " AND pid=".$_COOKIE['lid']); ?>
}
This didn't work so I added some alerts to understand what was going on.
function like(id) {
<?php $_COOKIE['lid'] = "10"; ?>
alert("Like:" + id);
document.cookie="lid="+id;
<?php query("INSERT INTO `likes`(`uid`, `pid`) VALUES (".$_SESSION['id'] . ",".$_COOKIE['lid'].")"); ?>
alert("<?php echo $_COOKIE['lid']; ?>");
}
function dislike(id) {
<?php $_COOKIE['lid'] = "10"; ?>
alert("Dislike:" + id);
document.cookie="lid="+id;
<?php query("DELETE FROM `likes` WHERE uid=".$_SESSION['id'] . " AND pid=".$_COOKIE['lid']); ?>
alert("<?php echo $_COOKIE['lid']; ?>");
}
The first alert showed the correct id, but the second alert showed "10".
What did I do wrong?
How should I transfer the id from JavaScript to PHP?
Is there an other good way to run PHP code when someone clicks on a button without the newsfeed going back to the top?
Thanks