I want to add values to the existing array variable inside my cookie.
Currently I set my cookie using Ajax:
Ajax:
function setcookie(productid){
$.ajax({
type: 'POST',
url: "setcookies.php",
data: {
id: "productid"
},
success: function (e) {
alert(e);
}
});
}
PHP setcookies.php
<?php
$cookiename = "products";
$cart = array();
$pid = $_POST['id'];
array_push($cart, $pid);
setcookie($cookiename, serialize($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = serialize($cart);
When I click addproduct button setcookie() function will be called. Clicking addproduct button three times I expected that 3 ids of the product should be added to the cookie array but when I access the page that will show the cookies in my page it will just only show the last productid added.
Thank you in advance guys.
EDIT FOR MY WORKING CODE:
Below code works in my end: Just slightly modified the code answered by Dominique.
$cookiename = "products";
$cart = null;
$pid = $_POST['id'];
if (!empty($_COOKIE[$cookiename])) {
$cart = unserialize($_COOKIE[$cookiename]);
array_push($cart, $pid);
} else {
$cart = array();
array_push($cart, $pid);
}
setcookie($cookiename, serialize($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = serialize($cart);