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":

1
$.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:

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

If the page requested is http://www.example.com/file.html then it will be set for the / path and will be available for all paths at the domain. If the page is http://www.example.com/subpath/file.html 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:

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

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

No comments:

Post a Comment