Antonios Tsimourtos
Antonios Tsimourtos

Reputation: 1672

Setting cookies doesn't work as expected

What i am trying to accomplish :

When a href is pressed i call the saveItem() function. It is called as below :

<a href="#" class="save-product" onclick="saveItem('savedList', '<?php echo get_the_ID();?>', 90)">

savedList = the name of my cookie

get_the_ID() = A wordpress function to get the current's ID post, '185' etc.

90 = the days for the cookie to expire

When saveItem() is called, it checks if a cookie with name savedList already exists. If it doesn't, it creates a cookie with that name and adds the value which is passed through the parameter(the id of current post). When this cookie exists, i want to add to that cookie one more id and the delimiter would be ; so i can - in another page show a list of products through that cookie's list.

So my cookie has "185" . When i add a new ID, for example "65", i want my cookie to become "185;65"

My problem is that it doesn't work as expected. The weird thing is that if i see on the console.log("New Value Is : " + newValue); it shows "185;65" but console.log(mNameList); shows only "185" again.

To check my cookie's value i use :

print_r($_COOKIE['savedList']);

Functions below :

saveItem():

function saveItem(name,value,days) {

    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }

    // Get Cookie
    var mNameList = getCookie(name);

    // If cookie is empty - doesn't exist then create it and put the value given
    if (mNameList == "") {
        document.cookie = name + "=" + value + expires + "; path=/";
    } else {

        // If cookie exists, check if it has already this value, if it doesn't then add oldvalue + new value to that cookie.
        if(mNameList !== value){
            var newValue = mNameList + ';' + value; // "185;65"
            document.cookie = name + "=" + newValue + expires + "; path=/"; 
            console.log("New Value Is : " + newValue);
            var mNameList = getCookie(name); // Το check current cookie get it again
            console.log(mNameList); // Show it - here it shows "185"
        }
        else{
            // Value already exists in cookie - don't add it
            console.log("Are same - mNameList->" + mNameList + "  |   currentID->" + value);
        }
    }
}

Getcookie();

function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

Upvotes: 0

Views: 101

Answers (2)

Antonios Tsimourtos
Antonios Tsimourtos

Reputation: 1672

Ok so the problem was in the delimiter and in my code too - the way i was checking if ID already exists was wrong but the below works.

saveItem()

function saveItem(name,value,days) {

        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }

        var mNameList = getCookie(name);

        if (mNameList == "") {
            document.cookie = name + "=" + value + expires + "; path=/";
        } else {

            var doesItemExists = false;
            var partsOfStr = mNameList.split('-');

            for(var i =0; i < partsOfStr.length; i++){
                if(partsOfStr[i] == value)
                    doesItemExists = true;
            }

            if(!doesItemExists){
                var newValue = mNameList + '-' + value;
                document.cookie = name + "=" + newValue + expires + "; path=/";
                console.log("New Value Is : " + newValue);
            }
            else{
                console.log("Are same - mNameList->" + mNameList + "  |   currentID->" + value);
            }
        }
    }

Upvotes: 0

Bj&#246;rn
Bj&#246;rn

Reputation: 489

As you do it yourself ; is the field delimiter in a cookie between value, expiration etc. You cannot use it to seperate your values.

Upvotes: 1

Related Questions