3

I am trying to get the value of a cookie into a global variable in which I can then place into div's by using document.getElementById.

Here is my code - it works prefectly in terms of the fact it remembers the cookie but it just won't do one line in particular which I have clearly outlined with a comment for you.

Here is all my code...

<!DOCTYPE HTML>
<html>
<head>
    <script>
        var globalVar = "";

        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }

        function getCookie(cname) {
            var name = cname + "=";
            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);
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }

        function checkCookie() {
            var user = getCookie("username");
            if (user != "") {
                alert("Welcome again " + user);
                globalVar = getCookie("username");
                document.getElementById("demo").innerHTML = globalVar; /* THIS LINE DON'T WORK WHY NOT! THE ONE BELOW DOES IN THE CHANGE COOKIE FUNCTION DOES! */
            } else {
                user = prompt("Please enter your name:", "");
                if (user != "" && user != null) {
                    setCookie("username", user, 30);
                }
            }
        }

        function changeCookie() {
            var user = getCookie("username");
            user = prompt("Please enter your name:", "");
            if (user != "" && user != null) {
                setCookie("username", user, 30);
            }
            document.getElementById("demo").innerHTML = user; /* THIS WORKS! */
        }
        checkCookie();
    </script>
</head>
<body>
    <div id="demo"></div>
    <button onclick="changeCookie()">Change username</button>
</body>
</html>
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
  • console log the cookie see if it has any value – madalinivascu Mar 24 '16 at 08:12
  • Its working for me here, the same and exact code. It seems that you are using Chrome browser which by default don't allows to set cookie until and unless you are running the file from a host or domain. Try it in firefox it will work. Please note: Initially you are just setting cookie and not putting it into html. The line which you stated as not working actually will put the content in html only when user comes back again. i.e. You reload the page. And i hope this what you are expecting logically. – Luke P. Issac Mar 24 '16 at 08:43
  • I was trying it in IE actually but yes I know it doesn't work in Chomre which just makes me so mad @Luke P. – Please Help Mar 24 '16 at 08:56
  • LOL My question was not a duplicate as far as I was aware as I searched stackoverflow forums for help for over 2 hours as I was stuck in a shopping centre with nothing to do... so @Quentin I have no idea what you are referring to. I would like to see a link to this so called "duplicate" please. – Please Help Mar 24 '16 at 09:06
  • Lol nevermind mine has nothing to do with jquery, thats why i considered it irrelevant – Please Help Mar 24 '16 at 09:06

2 Answers2

1

Try calling checkCookie() right after the page has finished loading.

<body onload="checkCookie()">

Another way is to move the script tag to the end of the page, right before the closing tag of body like this:

<html>
<body>
   <div id="demo"></div>
   <button></button>

  <!-- the rest of the page's HTML here -->

   <script>
      ....
      .... your script code here
      ....
      ....
      checkCookie();
   </scirpt>
</body>
</html>
Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • 1
    The complete reason why it doesn't work is that the HTML is not loaded yet when `checkCookie` is called, throwing a very explicit error: `Uncaught TypeError: Cannot set property 'innerHTML' of null`. – dashdashzako Mar 24 '16 at 08:20
-1

You are only assign html into "demo" in the first part of the case statement, you need to add it to the second part, and assign the user variable, not the globalVar. Also place the code at the end of the body as suggested in other answers.

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
        globalVar = getCookie("username");
        document.getElementById("demo").innerHTML = globalVar; 
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
           document.getElementById("demo").innerHTML = user;
       }
    }
}