0

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?

  • Use the developer console to check if the cookie is there. – Matt R Oct 29 '15 at 15:37
  • It is there when I click the button, but once I refresh the page it is no longer there. – MindYaBidness Oct 29 '15 at 15:42
  • Can you confirm the expire date of the cookie, when there, is indeed 30 days from now and not set to `Session`? – ZiNNED Oct 29 '15 at 15:45
  • @ZiNNED I use the get and set Cookie functions on other pages of my site and it is working as it should. So I believe my expiration date is correct. Another reason why this is confusing me so much. – MindYaBidness Oct 29 '15 at 15:51

1 Answers1

0

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.

Community
  • 1
  • 1
  • It appears that my readCookie/getCookie is turning up empty... but I use this function else where on my site and it returns the appropriate value. Sooo what the hell – MindYaBidness Oct 29 '15 at 16:32
  • What's your browser (and its version) ? Try with another one to know if it's from your code or your browser. – Michael Faurel Oct 30 '15 at 08:30