Blob
Blob

Reputation: 97

javascript how to set and retrieve a cookie simple

I have been looking at some sites about js cookies such as:

http://www.w3schools.com/js/js_cookies.asp
http://www.quirksmode.org/js/cookies.html Cannot list more links because of reputation.

I could not find anymore useful websites. The ones above don't work for me or are too complicated. I have found the quirksmode website useful but it didn't work. Here's the code I made to test it:

<html>
<head>
<script>
function read() {
    var x = readCookie('scon')
    if (x) {
        alert(x);
    }
}

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 createCookie() {
    document.cookie = 'scon=testcookie; expires=Thu, 17 Jan 2013 13:47:11 UTC; path=/'
}   


</script>
    <title>Page Title</title>
</head>
<body>
<button onclick="createCookie()">Create</button>
<button onclick="read()">Read</button>

</body>
</html>

Please can you see whats going wrong and try to explain why and which bit does what if possible. This is going to be used as a standard cookie to save a setting.

Upvotes: 0

Views: 991

Answers (1)

Joseph
Joseph

Reputation: 1086

What website browser are you using?

If you are using Firefox then it should just work, but Chrome and maybe others don't support "local" cookies... meaning that you have to run the JavaScript on an actual local server or on an actual web host.

Try running your code in the latest Firefox... it worked for me.

Hope that makes sense

Upvotes: 2

Related Questions