4

Looking to create a cookie where it holds the name of the person looking to take a quiz.

It will ask for the user when the page loads, but it doesn't remember the cookie when I reload the browser.

Anyone have any idea why?

Sorry, I know it is a really basic question. Trying to teach myself about cookies with Javascript.

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<style>
h1, h2{
    margin-top: 150px;
    text-align: center;
    font-family: Arial, Helvetica, sans-serif;
}
p {
    margin-bottom:0px;
    text-align: center;
}
.button {
    padding: 20px 20px;
    border-radius: 15px;
    font-size: 14px;
    cursor: pointer;
    margin-left: 100px;
    margin-top: 50px;

}
#banner{
     padding:0 145px;
}
#banner img{
     display:block;
     margin:0 auto;
}
div.buttonGroup{
    margin-left: 450px;
}
body {
    background-color:#ffdab3;
}
</style>
<meta charset="UTF-8">
</head>

<body onload checkCookies()>

<script>
function setCookie(cname, cvalue, exdays) {

    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue  +";" + expires + ";path=/";
}

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

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}
</script>
</body>
</html>
3
  • Are you loading the page with http:// or file:///? Commented Apr 15, 2018 at 16:30
  • @raul.vila I'm loading it with file:// is that an issue? Commented Apr 15, 2018 at 16:31
  • 1
    @raul.vila I have it saved to my htdocs folder in my xampp location so tried with the local host and it worked! I will do some research on the differences though thank you for helping! If you want to write it as an answer and I can select it as correct. Commented Apr 15, 2018 at 16:34

1 Answer 1

2

@raul.vila don't load the page in a static manner (try with a local server). It would work then

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.