Cookies not being remembered

I’m trying to get my head around cookies. I have read several web sites for help and came up eventually with this:

<!doctype html>
<html>
<head>
  <title>Cookie test</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <script>
    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("Hello again " + user);
      } else {
        user = prompt("Please tell me your name:","");
        if (user != "" && user != null) {
          setCookie("username", user, 30);
        }
      }
    }
  </script>
</head>
<body onload="checkCookie()">
  <p>This is a cookie test</p>
</body>

</html>

When I call this html file I get the prompt for my name. Then I close the page, reopen it and get another request for my name. What I expected was the “Hello again” message.
What am I doing wrong?

Sorry I screwed that up! How to I insert HTML into a post?

You have to put it inside 3 backticks like so, I’ve edited your post to correct the code output

```




```

Thanks a lot. As you may have guessed, I’m new to this game!

A previous answer to this problem may help you.
Keep Checkboxes Checked

Have a look at the JSFiddle link for an example program. :grinning:

I’ve looked at the material you suggested, but I still can’t get mine to work.
Can you please tell me what is wrong with my code as originally posted?
Thanks, Ken

Do you have your browsers cookie settings to remove cookies when the browser closes?

(Sorry for the delay in replying. We veterans never have enough time for all our trivia!)

All the browsers I use (mainly Opera and MS Edge on a Windows 10 laptop) work normally with other sites’ cookies (i.e. they remember them), but not the stuff I’ve tried. Do I have to get my service provider to tweak my account? In any case, what’s wrong with my original code? (It is just a little test file, so is incomplete,)

Thanks, Ken

Still no reply to my original question: what’s wrong with my original code?

script in the head instead of at the bottom of the body
use of debugging alert and prompt calls to display messages instead of console.log
JavaScript jumbled with HTML instead of in separate file

probably a lot more but those are the most obvious

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.