jQuery Cookie problem – persistence and duplication

I’ve started to use cookies to maintain user state and the jQuery Cookie plugin provides simple functions to create, read and delete cookies. However, I came across a problem where state didn’t appear to be persisting and on viewing the cookie information, using the web developer toolbar, I had multiple versions of the same cookie.

Background

When a cookie is created normally (without the plugin), its path will normally default to "/" meaning that the cookie is valid throughout the whole domain.

It means that should you want to, cookies can be set per directory and they will be valid to a certain set of pages, i.e. set the path of the cookie to "/help" and all your help pages will have access to that cookie but none of those pages in, for instance, /home.

The solution

The problem occurs because jQuery Cookie sets its defaut path as the path the user was at when the cookie was created. The developer must explicitly set the cookie’s path as "/" if top-level domain access is what they’re after.

Instead of a simple name, value pair:

$.cookie('the_cookie', 'the_value');

You will need the slightly less simple addition of an argument:

$.cookie('the_cookie', 'the_value', { path: "/" });

Further reading

Tags: ,

5 Responses to “jQuery Cookie problem – persistence and duplication”

  1. David says:

    You saved the day!!! I’ve been searching a fix for this for the past 3 hrs..thanks…great post!

  2. calculla says:

    Big thanks ! I was looking for that explanation :)

  3. Omprakash Dubey says:

    I am using Same thing… But in My web Application it is not Fixed from where the Cookie will Be Set, So is there any way that From Starting i can store it at Application Domain.. ?

  4. Manish says:

    Awesome!!!, Thanks a lot for explanation. Minor details matter a lot. I was having similar issues and it got fixed after i set the path.

  5. Archana says:

    This is very useful and saved my time. thanks

Leave a Reply