Wednesday, September 5, 2012

Setting cookies with jQuery

Set a cookie
Setting a cookie with jQuery is as simple as this, where a cookie is created called "example" with a value of "foo":

$.cookie("example", "foo");
This is a session cookie which is set for the current path level and will be destroyed when the user exits the browser. To make the same cookie last for e.g. 7 days do this:

$.cookie("example", "foo", { expires: 7 });
Note: the above examples will apply the cookie to the current path level.

If the page requested is then it will be set for the / path and will be available for all paths at the domain. If the page is then it will be set for the /subpath level and will not be accessible at / (or /otherpath etc).

To explicitly make the cookie available for all paths on your domain, make sure the path is set:

$.cookie("example", "foo", { path: '/' });
To limit it to a specific path instead:

$.cookie("example", "foo", { path: '/admin' });