...

View Full Version : Javascript cookies getCookie function



NoobFoo
07-30-2011, 11:15 PM
I'm running into a bit of problems trying to use some JS cookies. I have 2 values I want stored and have created the following set cookie function
setCookie(Name, amountCorrect, totalAmountCorrect, max-age)
{ document.cookie = "averageScore" + quizAverageIncrement + totalCorrect +"; max-age=" + 1000 * 60 * 60 * 24 * 30 +"; path=/; } Now I want to read the cookie and use the values from the two variables "averageScore" and "quizAverageIncrement" I'm not sure exactly how to be able to use the values of those two variables since they have been concatenated into a string when the cookie is made (I think). So I would like to start with
function getCookie(averageScore) { // if cookie is blank on first iteration do nothing else retrieve values I need. \n if (document.cookie.length > 0 Thats all I have please point me in the right direction to retrieve these values and use them in my JS elsewhere.

Krupski
07-31-2011, 04:31 AM
I'm running into a bit of problems trying to use some JS cookies.

Use these:



/***
* write a cookie: name, value, lifetime in days
* set days = 0 to delete cookie
**/
var writeCookie = function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 86400000));
var expires = '; expires=' + date.toGMTString();
} else {
expires = '';
}
var content = name + '=' + value + expires;
document.cookie = content;
return content;
}

/***
* read a cookie: name. returns value or false if not found
**/
var readCookie = function (name) {
var ne = 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(ne) == 0) {
return c.substring(ne.length, c.length);
}
}
return false;
}



No point re-inventing the wheel......

bullant
07-31-2011, 08:55 AM
looks like krupski got those functions from the same place I got these on the www :)


var cookieEnabled = false;
cookieEnabled=(navigator.cookieEnabled)? true : false
//if not IE4+ nor NS6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}

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

function readCookie(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;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

NoobFoo
07-31-2011, 01:21 PM
Thanks for the help and I think I'm on my way, however it seems the cookies are not being set properly. When I try to access the values for quizAverageIncrement and totalAmountCorrect as shown in my code below they retain the original values they have when they were initialized. I have cookies enabled and security set to the lowest. The code is within the script tags and no error shows on the status bar. Any suggestions as to why my cookie is not being set?



var readCookie = function (name) {
////// line200
var ne = 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(ne) == 0) {
return c.substring(ne.length, c.length);
}
}
return false;
}

var writeCookie = function (name, value, value2, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 86400000));
var expires = '; expires=' + date.toGMTString();
} else {
expires = '';
}
var content = name + '=' + value + value2 + expires;
document.cookie = content;
return content;
}


readCookie("averageScore");

quizAverage = totalAmountCorrect / quizAverageIncrement;

if (quizAverage == 0) {
strRes3 = "<h2 align=center><br>";
strRes3 += "Not enough data for average score yet" + "</h2><br><br><br>";
document.write(strRes3); }
else {
quizAverage = totalAmountCorrect / quizAverageIncrement;
strRes4 = "<h2 align=center><br>";
strRes4 += "The average score is:" +quizAverage + "%" + "</h2><br><br><br>";
document.write(strRes4); }


quizAverageIncrement += 5;
totalAmountCorrect += rights;

writeCookie ("averageScore", quizAverageIncrement, totalAmountCorrect, 30);

Krupski
07-31-2011, 05:08 PM
looks like krupski got those functions from the same place I got these on the www :)


Well I got them from my PHPBB3 message board code.

I modified them to not use the PHPBB specific variables before I posted them.

I suppose if you ask 100 programmers to develop cookie read and write code, you will get 100 very similar pieces of code since it's so simple.

;)

Krupski
07-31-2011, 05:12 PM
Thanks for the help and I think I'm on my way, however it seems the cookies are not being set properly.

Why did you change the code? If you want to save and read two different values, use two separate calls to the code.

You could do something like:



var age = 54;
var name = roger;

writeCookie ('age', age, 7); // save cookie for 7 days
writeCookie ('name', name, 7);

alert(readCookie('age')); // shows 54
alert(readCookie('name')); // shows roger

NoobFoo
07-31-2011, 06:58 PM
I didn't know any better hence the name "NoobFoo" lol. Now it is working however I have one last issue. the variable in the cookie using your example age keeps getting initialized back to its original value. Using the write and read cookie methods above:



var age = 54;

age = parseInt(age) + 6; //perform some calculation on age

writeCookie ("age", age, 7); // write the cookie

alert(readCookie("age")); // shows 60 as intended
//Now I want to close the browser, then re-open and retrieve the value 60
// Problem is the variable age will get reinitialized back to 54 again.


I need to work with the value retained in the cookie. Only initializing it once
and then work with the new value. Is that possible? I really appreciate the help

Logic Ali
07-31-2011, 09:19 PM
If in the absence of the cookie, age should have a default value, you could have:

var age = readCookie("age") || 54;

bullant
08-01-2011, 01:00 AM
Well I got them from my PHPBB3 message board code.

I modified them to not use the PHPBB specific variables before I posted them.


No problem :)

I wasn't sure if you were trying to create the impression that the code you posted was originally written by you.

NoobFoo
08-01-2011, 06:31 PM
Well won't that the statement be reinitialized when it the script is loaded again. It is going to perform that action again. I need to initialize it first.

Here is the pseudo code.
readCookie(age) // age doesn't have a value and will be null unless I initialize
var age = 54; // initialize and assign first value to it
parseInt(age) + 6; //now the value is 60
writeCookie(age) ; //Now the value 60 is stored in the cookie

Now I close the application and browser. Later I reopen the application and
browser so I reload the cookie. Now here is the second iteration.

readCookie(age) // Age now has the value of 60 as intended.
var age = 54; // Uh oh now the code is reinitialized back to 54
parseInt(age) + 6; //now the value is 60 I want the value 66 instead and to be able to continue to increment it on ever iteration (not really an iteration it isn't a loop but I mean every time the program is opened again and the stored cookie is retrieved.
writeCookie(age) ; //Now the value 60 is stored in the cookie

Logic Ali
08-02-2011, 02:56 AM
var age = parseInt( readCookie( "age" ) ) || 54;

alert( "Age is " + age );

writeCookie( "age", age + 6, 7 );



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum