4

I'm trying to use Javascript to update some cookies for a website. It should look to see if an existing cookie as a certain value. If so, delete the cookie and replace it.

Instead, it's adding the new cookie without removing the original.

Here's my code

$(document).ready(function(){
if(getCookie('ref') == 'na') {
    $.cookie('ref', null, { path: '/', expires: -5 });
    $.cookie('ref', Base64.encode(document.referrer), { expires: 365 });
}

});

Here's the cookie library I'm using: https://github.com/carhartl/jquery-cookie

What am I doing wrong?

1 Answer 1

2

To delete a cookie, you must set it with the exact same path and domain you intend to delete it from. Specify the path in both $.cookie() calls, and if the domain was specified in any previous code, the domain must be specified as an exact match in the jQuery code.

$(document).ready(function() {
  if(getCookie('ref') == 'na') {
      $.cookie('ref', null, { path: '/', expires: -5 });
      $.cookie('ref', Base64.encode(document.referrer), {path: '/', expires: 365 });
  }
});

However, there is no real need to delete the cookie if you just intend to overwrite it:

$(document).ready(function() {
  if(getCookie('ref') == 'na') {
    // Just write the new cookie over the old one...
    $.cookie('ref', Base64.encode(document.referrer), {path: '/', expires: 365 });
  }
 });
2
  • i think the path is the problem. When I set the cookie in PHP it's adding a period to the beginning of the domain name. I think that's why JS doesn't overwrite it.
    – liz
    Jul 30, 2012 at 21:26
  • @liz Yes, the domain like the path must be an exact match when you attempt to overwrite a cookie. Jul 30, 2012 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.