0

I'm having problem of creating a cookie, I have this code:

window.onload = function() {

var value = readCookie('username');
if(value == null){
    alert("null");
    document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";
}
else
    alert(value);   

}

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

When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.

UPDATE So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.

  • what is this code doing `while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);` – Asad May 10 '16 at 13:06
  • https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework – epascarello May 10 '16 at 13:06
  • @Asad don't know exactly, I saw the code here: [w3school](http://www.w3schools.com/js/js_cookies.asp) –  May 10 '16 at 13:22
  • Does it work if you use a real date? – Quentin May 10 '16 at 13:23
  • @Quentin tested now, doesn't work –  May 10 '16 at 13:25
  • @Azazel There are some good libraries to handle this kind of problem. If you can use Jquery on your page give a try to https://github.com/js-cookie/js-cookie – Victor May 10 '16 at 13:28
  • I just created a test page using the code from the question. The first time I loaded the page, it alerted `null`, the second time `Bob`. Whatever the problem is, it isn't exposed by the code in the question. – Quentin May 10 '16 at 13:29
  • @Quentin it's some problem of the browser then? I'm using Chrome. –  May 10 '16 at 13:35

2 Answers2

1

When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.

If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.

Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.

You are presumably loading them from a local file, and that is where the problem lies, not with your code.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Try this function for reading cookie. I've been using it for quite too long and it's working fine so far

function getCookieValue(cookie_name) {
    var cookie, cookies = document.cookie.split(';');

    for (var i = cookies.length - 1;  i >= 0;  --i) {
        cookie = cookies[i].split('=');
        if (cookie[0].trim() === cookie_name)
            return cookie[1];
    }

    return "";
}

Also if you are interested you could use this function for adding cookies for 10 years.

function addCookie(name, value) {
    var expire = new Date();
    expire.setFullYear(expire.getFullYear() + 10);
    d.cookie = name + "=" + value + "; expires=" + expire.toGMTString() + "; path=/";
}
Kamen Stoykov
  • 1,715
  • 3
  • 17
  • 31
  • What's wrong with the existing code that this would fix? – Quentin May 10 '16 at 13:27
  • Let's say that there could be more than 1 white space at the beginning, that why it's better to use trim() – Kamen Stoykov May 10 '16 at 13:28
  • The code in the question doesn't put more than 1 white space at the beginning, so let's not say that. – Quentin May 10 '16 at 13:29
  • Also you are returning all cookie data (expire time, domain and so on) which will need additional parsing. – Kamen Stoykov May 10 '16 at 13:30
  • And one main problem is that you are not setting "path" which adding cookie. Try to set it or just use function which I gave you :) – Kamen Stoykov May 10 '16 at 13:31
  • Also try to replace UTC format with GMT... You could try functions which I gave you for 1min and check if everything is working. It will just save time... – Kamen Stoykov May 10 '16 at 13:32
  • The path parameter in a cookie is optional. It might matter if the OP was trying to read the cookie on a different page, but they aren't here, so that can't be the problem. – Quentin May 10 '16 at 13:32
  • 1
    @KamenStoykov I tried your code but the alert of value I return getCookieValue() its empty. –  May 10 '16 at 13:33
  • I have just tested both function and they are working. Did you try both of them or just getCookieValue() ? Just one more comment for date... 18th of December 2016 is Sun, not Thu. Try to change this too. – Kamen Stoykov May 10 '16 at 13:36