JavaScript Cookie Length - javascript

I am just learning JS cookies. I am able to save the cookie when a person hits a button, but seems the length of period is not correct. I need it to be 15 days, but it keeps saying the length of time is until the end of the session (http://screencast.com/t/ea7TOoGTnbA).
Here is the code I am using below:
<script type="text/javascript">
function getCookie(w){
cName = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0] == w){
cName = unescape(NmeVal[1]);
}
}
return cName;
}
function printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + '; ';
}
}
return cStr;
}
function setCookie(name, value, expires, path, domain, secure){
document.cookie = name + "=" + escape(value) + "; ";
if(expires){
expires = setExpiration(expires);
document.cookie += "expires=" + expires + "; ";
}
if(path){
document.cookie += "path=" + path + "; ";
}
if(domain){
document.cookie += "domain=" + domain + "; ";
}
if(secure){
document.cookie += "secure; ";
}
}
function setExpiration(cookieLife){
var today = new Date();
var expr = new Date(today.getTime() + cookieLife * 60 * 60 * 10);
return expr.toGMTString();
}
</script>
<script language="JavaScript">
// set a cookie which will expire in 3 days and be accessible site wide
setCookie('drunkdriving_cta_overlay', 'Yes', 3, '/');
</script>
<script language="JavaScript"><!--
document.write(getCookie("drunkdriving_cta_overlay"));
//-->
</script>
<?php if (isset($_COOKIE["drunkdriving_cta_overlay"])) {?>
hello?
<?php } else { ?>
goodby
<?php } ?>
Any help would be greatly appreciated.

It looks like the problem is not in setting the cookie, but in the date calculation. Try replacing your setExpiration method with this:
function setExpiration(cookieLife){
var expires = new Date();
expires.setDate(expires.getDate()+cookieLife);
return expires.toGMTString();
}
The date calculation in your method does not seem to work correctly.
Edit:
Try this code instead. I think I found the issue.
<script type="text/javascript">
function getCookie(w){
cName = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split(';');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0] == w){
cName = unescape(NmeVal[1]);
}
}
return cName;
}
function printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split(';');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + ';';
}
}
return cStr;
}
function setCookie(name, value, expires, path, domain, secure){
var cookie = name + "=" + escape(value);
if(expires){
expires = setExpiration(expires);
cookie += ";expires=" + expires;
}
if(path){
cookie += ";path=" + path;
}
if(domain){
cookie += ";domain=" + domain;
}
if(secure){
cookie += ";secure";
}
document.cookie = cookie;
}
function setExpiration(cookieLife){
var expires = new Date();
expires.setDate(expires.getDate()+cookieLife);
return expires.toGMTString();
}
</script>
<script language="JavaScript">
// set a cookie which will expire in 3 days and be accessible site wide
setCookie('drunkdriving_cta_overlay', 'Yes', 3, '/');
</script>
<script language="JavaScript"><!--
document.write(getCookie("drunkdriving_cta_overlay"));
//-->
</script>

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

Cookie values consistently returning null

I'm attempting to use a prompt to have someone enter a value, make that value into a cookie, then have a link that will redirect that person to a second page where their cookie value would be displayed. The issue I'm running into is that the cookie in question continues to be returned null, no matter what I input. Any help would be appreciated!
This is meant to be a Javascript code.
First Page (Prompt Page)
<!DOCTYPE html>
<html>
<head>
<title>Event Handlers</title>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = newDate();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString ();//code
}
else var expires = "";
cookieString = name + "=" + escape(value);
if (expires) cookieString += ";expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length, crumb.length));
//code
}
}
return null;
}
function deleteCookie(name) {
createCookie(name,"",-1);
//code
}
</script>
<script>
window.onload = function() {
var cookievalue = prompt("Cookie Value:");
createCookie("myCookieData", cookievalue);
}
</script>
</head>
<body>
Go to Cookie Test Page 2
</body>
</html>
Second Page (Display Cookie Page)
<!DOCTYPE html>
<html>
<title>Cookie Testing</title>
<head>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = newDate();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString ();//code
}
else var expires = "";
cookieString = name + "=" + escape(value);
if (expires) cookieString += ";expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length, crumb.length));
//code
}
}
return null;
}
function deleteCookie(name) {
createCookie(name,"",-1);
//code
}
</script>
<script>
window.onload = function () {
document.getElementById("output").innerHTML = "Your cookie value: " + getCookie("myCookieData");
}
</script>
</head>
<body>
Back to Cookie Test Page 1<br />
<div id="output"></div>
</body>
</html>
In addition, if anyone can give tips on to how to add a button to the second page to delete the cookies from the first page, that would also be greatly appreciated! But for now, I'd just like to figure out why my cookies keep being returned null. Thanks in advance!
Cookies are not allowed in local files on some browsers. So if you're using local files - try uploading those files to a server and trying again. Works for me.
To add a cookie delete button you can use:
<input type="button" onClick="deleteCookie('myCookieData')" />

JavaScript Cookies i'm getting NaN property

I tried to save a number in javascript in document.cookie.
But when i try to get a cookie with a number i'm always getting NaN when i try to display it
var playerCoffeeCount = 0;
function setCookie(c_name, value, exdays) { //Setting a cookie (just a shortcut for making cookies)
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) { //Getting a cookie (another shortcut)
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function saveGame(){
setCookie("playerCoffeeCookie", playerCoffeeCount, 999);
}
function loadGame(){
playerCoffeeCount = getCookie("playerCoffeeCookie");
}
function displayCookie(){
document.getElementById("coffeecount").innerHTML= "Coffee: " + Math.floor(playerCoffeeCount);
}
This cookie system in JavaScript saves the value, but it displays as a NaN... Please help :(
try this, working good.
function createCookie(name,days,value) {
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=/";
}
function readCookie(name) { //cookie reader function
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;
}
function eraseCookie(name) { //cookie eraser function
createCookie(name,"",-1);
}
createCookie("test", 1, 1);
var mycookie= readCookie("test");
mycookie = parseFloat(mycookie);
console.log(mycookie);
I just found out you just have to disable autosave then hard reset then immediately exit out the tab and if it doesn't work keep trying till it does

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

Categories

Resources