Reputation: 315
hi i want to set a cookie on button click but i have a problem with it
this is my first version of code and it is working fine
<?php
$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;
$cookie_name = "favoritepost";
if ( isset($_COOKIE[$cookie_name]) ) {
$kookie = unserialize($_COOKIE[$cookie_name]);
} else {
$kookie = array();
}
if ( ! in_array($ID, $kookie) ) {
$kookie[] = $ID;
}
setcookie($cookie_name, serialize($kookie), time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
then as i said i wanted to change the cookie set as button click so i wrote this code but it is not workinf and it gives me no cookie set what is the problem. thanks
<!doctype html>
<?php
$ID = is_numeric($_GET['ID']) ? $_GET['ID'] : 1;
$cookie_name = "favoritepost";
if ( isset($_COOKIE[$cookie_name]) ) {
$kookie = unserialize($_COOKIE[$cookie_name]);
} else {
$kookie = array();
}
if ( ! in_array($ID, $kookie) ) {
$kookie[] = $ID;
}
?>
<button type="button" onclick="setcookie('<?php echo $cookie_name;?>', '<?php echo serialize($kookie);?>', time() + (86400 * 30), "/")">Click Me!</button>
<html>
Upvotes: 0
Views: 2361
Reputation: 8022
You're mixing JS and PHP, and it's a deadly combination. JS is a client-side language where as PHP is a sever side language.
Every thing you write in PHP is executed server and everything your write in JS is executed client side.
First solution is use AJAX calls to connect PHP script with JS. Call AJAX function on click of a button which calls PHP script on server side to save the cookie.
Reference: http://www.w3schools.com/PHP/php_ajax_php.asp
Another solution is perform operations on client side only to save/retrive cookie.
Reference: http://www.w3schools.com/js/js_cookies.asp
Doing it on server-side is preferable as it gives more security then client side code.
Upvotes: 1