SetCookie with Javascript

I am trying to setCookie on a wordpress page load. Unfortunately nothing is happening when I added the script code below. I’ve been using this code in php setcookie("gmp_", "1", strtotime( '+30 days' ), '/'); with no problems but now I’m trying to get the Javascript version to work. Am I overlooking something?

<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=/";
}
setCookie('gmp_','1',30);    
</script>

Related posts

Leave a Reply

2 comments

  1. Notes the space after ; in split.

    function ReadCookie()
    {
       var allcookies = document.cookie;
       alert("All Cookies : " + allcookies );
    
       // Get all the cookies pairs in an array
       cookiearray  = allcookies.split('; '); //notes the space after ;
    
       // Now take key value pair out of this array
       for(var i=0; i<cookiearray.length; i++){
           name = cookiearray[i].split('=')[0];
           value = cookiearray[i].split('=')[1];
           alert("Key is : " + name + " and Value is : " + value);
       }
    }
    
  2. Your code is seems to be working fine…. the value of cookie is getting saved in your variable gmp_ with value is equals to 1.

    You can check your saved cookie values by the following JS function..

    function ReadCookie()
    {
       var allcookies = document.cookie;
       alert("All Cookies : " + allcookies );
    
       // Get all the cookies pairs in an array
       cookiearray  = allcookies.split(';');
    
       // Now take key value pair out of this array
       for(var i=0; i<cookiearray.length; i++){
          name = cookiearray[i].split('=')[0];
          value = cookiearray[i].split('=')[1];
          alert("Key is : " + name + " and Value is : " + value);
       }
    }