Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Cookies are not being set

I followed went through some related threads and also followed the tutorial on http://www.quirksmode.org/js/cookies.html but I can't get my cookie to set.

<script type="text/javascript">
function setcookie(name, value, days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+days*24*60*60*1000));
        var expires = "; expires="date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="value+expires+;path=/";
}
</script>

Then in my tag I have:

<body>
<script type="text/javascript">
    setcookie("testcookie", "test", 1);
</script>
</body>

Any ideas where I'm going wrong? I have cookies enabled, using FF and I can see cookies being created in real time by sites like Youtube but this one won't set at all.

like image 495
Seth Avatar asked Dec 22 '22 06:12

Seth


2 Answers

The script contains several mistakes. Here's the corrected version (tested):

function setcookie(name, value, days)
{
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime()+days*24*60*60*1000); // ) removed
    var expires = "; expires=" + date.toGMTString(); // + added
  }
  else
    var expires = "";
  document.cookie = name+"=" + value+expires + ";path=/"; // + and " added
}
like image 89
Yogu Avatar answered Jan 06 '23 00:01

Yogu


You are missing a + sign and a quote mark on this line:

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

should be:

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

I'd suggest you look in your browser's error console or your javascript debugger's console to see javascript errors.

like image 27
jfriend00 Avatar answered Jan 06 '23 00:01

jfriend00