简体   繁体   中英

Why isn't my cookie storing?

I'm trying to set a cookie on a click event to see if a user has actually clicked the respective button. The button is as follows:

<a href="#/" class="button" id="modalBTN">Click here</a>

My js to set the cookie is:

function setCookie(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires =" + d.toGMTString();
document.cookie = cname +"="+ cvalue + ";" + expires;
}

function getCookie(cname){
  var name = cname + "=";
  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);
    if(c.indexOf(name) == 0) return c.substring(name.length, c.length);
  }
  return "";
}

Then, I set the cookie on a click event:

$("#modalBTN").click(function(){
    var clicked = "clicked";
    setCookie("clicked", clicked, 30);

    console.log(clicked);
});

My click event works. when I console.log(clicked) I see the cookie value, but when I refresh the page the cookie is no longer there.

I check it by:

if(getCookie("clicked") != ""){
    //do something else
}

UPDATE

when I call getCookie("otherCookie") it works. But when I call getCookie("clicked") i get returned null. Am I only allowed to have one at a time?

Try this : https://stackoverflow.com/a/24103596/5445351

You can only use console to test the two functions : createCookie & readCookie

Do : createCookie('ppkcookie','testcookie',7);

Open another page, check if it's still there :

var x = readCookie('ppkcookie')
if (x) {
    console.log("ok");
}

Look if it's not your browser that delete cookies automatically. I tried with Chrome and IE9.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM