Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Javascript cookies getCookie function

    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
    Code:
     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
    Code:
     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.

  • #2
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by NoobFoo View Post
    I'm running into a bit of problems trying to use some JS cookies.
    Use these:

    Code:
    /***
     * 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......
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • Users who have thanked Krupski for this post:

    NoobFoo (07-31-2011)

  • #3
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    looks like krupski got those functions from the same place I got these on the www

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

  • Users who have thanked bullant for this post:

    NoobFoo (07-31-2011)

  • #4
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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?

    Code:
    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);
    Last edited by NoobFoo; 07-31-2011 at 03:48 PM.

  • #5
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by bullant View Post
    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.

    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #6
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by NoobFoo View Post
    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:

    Code:
    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
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #7
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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:
    Code:
     
    
    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

  • #8
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    If in the absence of the cookie, age should have a default value, you could have:
    Code:
    var age = readCookie("age") || 54;

  • #9
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Quote Originally Posted by Krupski View Post
    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.

  • #10
    New to the CF scene
    Join Date
    Jun 2011
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Continuing on with the same problem.

    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

  • #11
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Code:
    var age = parseInt( readCookie( "age" ) ) || 54;
    
    alert( "Age is " + age );
    
    writeCookie( "age", age + 6, 7 );


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •