iamj
iamj

Reputation: 183

PHP - Add value to existing array in cookie on button click

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);

Upvotes: 1

Views: 3403

Answers (2)

Dominique Vienne
Dominique Vienne

Reputation: 415

In your code, you instantiate $cart as an array containing 0 element and put it in $_COOKIE['products'] so it'll delete existing content.

It would explain why you could only have an array with a simple element.

This code should work

<?php
$cookiename = "products";

$cart = array();

if(!empty($_COOKIE[$cookiename])) {
    $cart = json_decode($_COOKIE[$cookiename], true);
}

$pid = $_POST['id'];
array_push($cart, $pid);

setcookie($cookiename, json_encode($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = json_encode($cart);

Upvotes: 7

Mohd Abdul Baquee
Mohd Abdul Baquee

Reputation: 449

<?php

$pid = $_POST['id'];
$cookiename = "products";

$cart = array();

if(isset($_COOKIE[$cookiename]) && !empty($_COOKIE[$cookiename])) {
    $cart = unserialize(base64_decode($_COOKIE[$cookiename]));
}

array_push($cart, $pid);

setcookie($cookiename, base64_encode(serialize($cart)), time() + 3600, "/");

//Your Cookie data output
$_COOKIE[$cookiename] = serialize($cart);

Upvotes: 1

Related Questions