0

For school work I need to use JavaScript to Save and read a cookie. The code for setting the cookie is all good, I got it from w3Schools (I know it's a terrible guide apparently). My problem is getting it to work with HTML/notepad using the "path" thing going on.

When the webpage loads a function called checkcookie checks if the cookie exists, if it doesn't, it asks the user to enter their name and then saves a cookie for later. If a cookie already exists, it displays a greeting message :). So far, I have made the functions work on the example running interface thing that you can access on w3schools. However, I recently tried setting them up using HTML documents, and the cookies don't seem to save properly. I open a NotePad document, paste the code, save as HTML, and open with Google Chrome. The pop-up asks for my name, I enter, but when I reload, the pop-up asks for my name again, and again, and so on. Here is the page I got the functions from: http://www.w3schools.com/js/js_cookies.asp

I think I need to sort out a path for the cookie, or something, I looked at this webpage for more info http://www.quirksmode.org/js/cookies.html but I still don't understand.

Why does this not work? Should I set the path to the file directory which the webpage's html documents are saved in? Why does it work in the w3schools TryIt system but not with raw HTML documents?

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

function getCookie(cname) {
    var title = cname + "=";
    var cookie_array = document.cookie.split(';');
    for(var i=0; i<cookie_array.length; i++) {
        var check = cookie_array[i];
        while (check.charAt(0)==' ') check = check.substring(1);
        if (check.indexOf(title) != -1) {
            return check.substring(title.length, check.length);
        }
    }
    return "";
}

function checkCookie() {
    var name=getCookie("name");
    if (name != "") {
        alert("Welcome again " + name);
    } else {
       name = prompt("Please enter your name:","");
       if (name != null && name != "") {
           setCookie("name", name, 30);
       }
    }
}
Jason
  • 47
  • 1
  • 1
  • 8
  • I think you need a web server to test cookies. You could use Apache other some other web server for that purpose. http://httpd.apache.org/download.cgi Once you're hosting your web page, you can use for example Chrome the view your cookies http://stackoverflow.com/questions/27201564/javascrip-cookie-save-form/27202745#27202745 – jyrkim Dec 01 '14 at 14:21

1 Answers1

0

Yep, as mentioned by jyrkim is a webserver thing

Jason
  • 47
  • 1
  • 1
  • 8