document.cookie sets the wrong path [duplicate] - 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;
}

Related

Cookies cannot read in wordpress

I created javascript cookie. But i can't read that cookie in wordpress. setcookie() function also not working. Only $_COOKIE is working .But it expiring in one minute.
You can use following javascript function to create, read and delete cookies
CREATE COOKIE
`
function createCookie(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 = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
`
READ COOKIE
`
function readCookie(name) {
var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
`
DELETE COOKIE
`
function eraseCookie(name) {
createCookie(name, "", -1);
}
`
Now, call javascript functions as:
createCookie('test','hello','5');
readCookie('test');
eraseCookie('test');

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

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/

writing cookie with a domain name

Below is the code I am writing to set the cookie with domain name= “.example.com” but this isn’t working. Any idea what’s wrong with the code? However if I remove the domain name, it works fine.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function setCookie(c_name,value,exdays)
{
alert("Cookie = " + document.cookie);
var c_value=escape(value);`enter code here`
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = c_name +"=" + value + ";expires=" + myDate + ";domain=.example.com;path=/";
}
</script>
</head>
<body onload="setCookie('name','value')">
</body>
</html>
Try these functions. It might help ;)
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
try this
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "; path=" + "/") +
((domain) ? "; domain=" + domain : "; domain=.example.com") +
((secure) ? "; secure" : "");
}

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