Setting cookies doesn't work as expected - javascript

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 "";
}

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

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

Related

document.cookie sets the wrong path [duplicate]

I am saving some cookie values on an ASP page. I want to set the root path for cookie so that the cookie will be available on all pages.
Currently the cookie path is /v/abcfile/frontend/
Please help me.
simply: document.cookie="name=value;path=/";
There is a negative point to it
Now, the cookie will be available to all directories on the domain it
is set from. If the website is just one of many at that domain, it’s
best not to do this because everyone else will also have access to
your cookie information.
For access cookie in whole app (use path=/):
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Note:
If you set path=/,
Now the cookie is available for whole application/domain.
If you not specify the path then current cookie is save just for the current page you can't access it on another page(s).
For more info read- http://www.quirksmode.org/js/cookies.html (Domain and path part)
If you use cookies in jquery by plugin jquery-cookie:
$.cookie('name', 'value', { expires: 7, path: '/' });
//or
$.cookie('name', 'value', { path: '/' });
document.cookie = "cookiename=Some Name; path=/";
This will do
See https://developer.mozilla.org/en/DOM/document.cookie for more documentation:
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
var sExpires = "";
if (vEnd) {
switch (typeof vEnd) {
case "number": sExpires = "; max-age=" + vEnd; break;
case "string": sExpires = "; expires=" + vEnd; break;
case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
}
}
document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
}
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}

Cannot set cookie to expire on browser close

I'm trying to set a cookie using javascript so it expires when the browser is closed.
I have the following function to do that:
function createCookie(value,days) {
var name = "name";
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
var cookie = name + "=" + value + expires + "; path=/";
document.cookie = cookie;
}
I tried many ways found here and there on the web like setting the date to "", setting it to yesterday (in that case the cookie is not even added) and omitting "expires" completly. I tried on Firefox and Chrome checking that every process was stopped before opening again, but the cookie is alway there.
What am I missing?
I am using this function for my self. It will work for you i gess :)
function createCookie(name, value, expiresInX_days, path) {
var a = new Date;
var expires = expiresInX_days || 1;
a.setTime(Date.now() + (1000 * 60 * 60 * 24 * expires));
var pt = path ? " ; path=" + path + ";" : ";";
return (document.cookie = name + "=" + value + ";" + "expires=" + a.toUTCString() + pt) ? !0 : !1;
}
If you want to delete your cookie, you can use this:
function rmCookie(cookieName){
var a = new Date;
a.setTime(0);
return (document.cookie = cookieName + "=;" + a.toUTCString()) ? !0 : !1;
}
If you want get your cookie clean,
function getMyFuckingCookie(cookieName){
var a = document.cookie.replace(/; /g, ";").split(";"),
b = a.length,
c = {},
nm = cookieName || !1;
while (b--) {
var d = a[b].split(/=(.+)/);
c[d[0]] = d[1];
}
return (nm) ? c[nm] : c;
}

SetCookie and expire time in one minute

I want to set input value in cookies and want alert in click function. Also I want to expiration date to cookies. I worked on cookies function but it is giving blank value. fiddle
function setCookie(c_name,value,extime)
{
var exdate=new Date();
exdate.setTime(exdate.getTime() + extime);
var c_value=escape(value) + ((extime==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Try this instead:
Set method:
function setCookie(name, value, days)
{
var expires;
if (days)
{
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else
{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
};
Get method:
function getCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++)
{
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
I've changed the jsfiddle respectively: http://jsfiddle.net/DVeVm/

Where is the bug in this cookie-clearing code?

Fiddle
Cookies.setCookie("x", "42");
var x = Cookies.getCookie("x");
alert("Meaning of life = " + x);
// BUG: This line does not in fact clear the cookie. Why?
Cookies.clearCookie("x");
x = Cookies.getCookie("x");
alert("Life should have no meaning : " + x);
And the Cookies code:
// This actually appears above, don't worry about undefined Cookies
Cookies = new function() {
var self = this;
self.getCookie = function(c_name, opt_domain) {
var i, name, value, cookies=document.cookie.split(";");
for (i=0; i < cookies.length; i++) {
name = cookies[i].substr(0, cookies[i].indexOf("="));
value = cookies[i].substr(cookies[i].indexOf("=")+1);
name = name.replace(/^\s+|\s+$/g,"");
if (name==c_name) {
if (opt_domain) {
if (!(value && value.indexOf(";domain=" + opt_domain) != -1)) {
continue;
}
}
return decodeURIComponent(value);
}
}
return null;
};
self.setCookie = function(c_name, value, opt_exdays, opt_domain) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + opt_exdays);
if (!opt_domain) {
opt_domain = document.domain;
}
var c_value = encodeURIComponent(value) + (opt_exdays? "; expires=" + exdate.toUTCString() : "") + ";path=/" + (opt_domain ? ";domain=" + opt_domain : "");
document.cookie=c_name + "=" + c_value;
};
self.clearCookie = function(c_name) {
// http://blogs.x2line.com/al/articles/316.aspx
var d = new Date(0).toUTCString();
document.cookie = c_name + "=deleted;expires=" + d + ";path=/";
};
};
I don't know for sure what the issue is with your code (it may be because you aren't setting at least the path), but according to this reference, an easier way of removing a cookie value is like this:
self.clearCookie = function(c_name) {
self.setCookie(c_name, "", -1);
}
It is because the domain is not specified.
If you change clearCookie to:
self.clearCookie = function(c_name) {
// http://blogs.x2line.com/al/articles/316.aspx
var d = new Date(0).toUTCString();
document.cookie = c_name + "=deleted;expires=" + d + ";path=/;domain=" + document.domain;
};
It clears the cookie (using document.domain).
Alternatively you can just call:
this.setCookie(c_name, "", -1);

How do I set path while saving a cookie value in JavaScript?

I am saving some cookie values on an ASP page. I want to set the root path for cookie so that the cookie will be available on all pages.
Currently the cookie path is /v/abcfile/frontend/
Please help me.
simply: document.cookie="name=value;path=/";
There is a negative point to it
Now, the cookie will be available to all directories on the domain it
is set from. If the website is just one of many at that domain, it’s
best not to do this because everyone else will also have access to
your cookie information.
For access cookie in whole app (use path=/):
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Note:
If you set path=/,
Now the cookie is available for whole application/domain.
If you not specify the path then current cookie is save just for the current page you can't access it on another page(s).
For more info read- http://www.quirksmode.org/js/cookies.html (Domain and path part)
If you use cookies in jquery by plugin jquery-cookie:
$.cookie('name', 'value', { expires: 7, path: '/' });
//or
$.cookie('name', 'value', { path: '/' });
document.cookie = "cookiename=Some Name; path=/";
This will do
See https://developer.mozilla.org/en/DOM/document.cookie for more documentation:
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
var sExpires = "";
if (vEnd) {
switch (typeof vEnd) {
case "number": sExpires = "; max-age=" + vEnd; break;
case "string": sExpires = "; expires=" + vEnd; break;
case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
}
}
document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
}
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}

Categories

Resources