TakeDown
TakeDown

Reputation: 75

How to use cookies with arrays and ajax?

i am trying to make a cart system for my (ecommerce) website and i can't figure out what i am doing wrong. I want to display some elements from cookies when the user clicks on a button. For the button, i am using some simple HTML:

<button onclick="test()">CLICK ME</button>

The javascript that i have attached to the function is this:

var httpRequest = new XMLHttpRequest();
    function test() {
         if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = alertContents;
        httpRequest.open('GET', 'test.php?q=<?php echo $row['denumire'];?>', true);
        httpRequest.send();
    }
    function alertContents() {
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                document.getElementById('test_adaugare_produs_cos').innerHTML = this.responseText;
            } else {
                alert('There was a problem with the request.');
            }
        }
    }

As i am in the testing phase, i just want to output the elements of the cookie in the page. If i have that working, the rest of my project is simple. The file test.php includes this code:

$cookie = $_COOKIE['cos'];
$produse = array("$cookie");
$q = $_GET['q'];
array_push($produse, "$q");
$produse = json_encode($produse);
setcookie("cos",$produse,time()+2592000);
$cookie = json_decode($_COOKIE['cos'], true);
foreach ( $cookie as $cook) {
    echo $cook;
    echo "<br>";
}

The code kinda works. It outputs the last element of the array, but the rest of the elements(which are just products names from the website, since the button should add the elements into the cart using cookies) are in a string format. This is what it looks like(after i click different products):

    ["[\"[\\\"[\\\\\\\"[\\\\\\\\\\\\\\\"[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"ABRAZIV PRO 115*50\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/100\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/ ML\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"]\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"ABRAZIV PRO 115*50\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/100\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/ ML\\\\\\\\\\\\\\\"]\\\\\\\",\\\\\\\"ACTUATOR MTR TECH2230\\\\\\\"]\\\",\\\"ACTUATOR MTR TECH2230\\\"]\",\"ACTUATOR MTR TECH2230\"]","ACCESORII SINA PLASTIC DUBLA 3M"]
ACCESORII SINA PLASTIC DUBLA 2.5M

The name of the products are as follow(i am including them because they aren't in english and i don't want to create confusion):

I have tried doing this kind of thing with arrays in cookies and just adding the product names to the array, but this proved troublesome. Would there be a better way? How should i fix this?

Thanks for your answers!

Upvotes: 0

Views: 190

Answers (1)

Greg Schmidt
Greg Schmidt

Reputation: 5099

It seems that $_COOKIE['cos'] is JSON encoded. But when you initialize $produse, you don't decode it, you're just initializing it with the encoded string. So, the array has a single element, which is encoded. Then you add another element to that, and then re-encode the whole thing. This will be why you get increasing numbers of slashes each time.

Try this:

$cookie = !empty($_COOKIE['cos']) ? json_decode($_COOKIE['cos'], true) : [];
$q = $_GET['q'];
array_push($cookie, $q);
$produse = json_encode($cookie);
setcookie('cos',$produse,time()+2592000);
foreach ($cookie as $cook) {
    echo $cook;
    echo "<br>";
}

Note that I've removed the double-quotes from around $q when pushing onto the array; they're not required, as $q is already a string.

If you want to eliminate some interim variables, you could do it like this:

$cookie = !empty($_COOKIE['cos']) ? json_decode($_COOKIE['cos'], true) : [];
array_push($cookie, $_GET['q']); // Alternately, $cookie[] = $_GET['q'];
setcookie('cos', json_encode($cookie), time()+2592000);
foreach ($cookie as $cook) {
    echo $cook;
    echo "<br>";
}

Upvotes: 1

Related Questions