I_Adze
I_Adze

Reputation: 89

Setting a cookie won't work javascript

I'm using the Javascript below to set a cookie but it doesn't set a cookie. Chrome's debugger gives me no errors and all the variables are correct. It just doesn't seem to set the cookie. document.cookie remains as "". Can anyone suggest why the cookie is not getting set?

function setCookie(name,value,exdays){
    var date=new Date();
    date.setTime(date.getTime()+(exdays*24*60*60*1000));
    var expires="expires="+date.toGMTString();
    document.cookie=name + "=" + value + "; " + expires + "path=/";
} // setCookie ends

If you need to know, I tried using the call setCookie("username","user",365);.

EDIT: added the missing "=", the code still doesn't work.

Upvotes: 0

Views: 3671

Answers (3)

ZomoXYZ
ZomoXYZ

Reputation: 1861

What I have found, is if you set the cookie a few times too quickly, then Chrome will stop the cookie from being updated at all. I have not tested this on any browser besides chrome. But the only way I have found to fix this is to completely quit Chrome and start it back up. After this the cookie for that page will be blank.

I am assuming this is some sort of security with Chrome, to make sure a third party/virus/bad advertisement doesn't interfere with your website's cookies. I couldn't find and documentation of this at all though, this is just a guess as to what is happening.

Upvotes: 0

Suman Bogati
Suman Bogati

Reputation: 6349

If you are runnig this code/file locally, then chrome does not set the cookie, If you will put it on remote server then it(page) will work.

For testing purpose you can run this page from xampp/htdocs.

Upvotes: 2

Satpal
Satpal

Reputation: 133453

You are missing = between name and value. Also, You need a semi-colon after expires

 document.cookie= name + "=" + value + "; " + expires + ";path=/";

Upvotes: 1

Related Questions