January 03, 2012

jQuery Cookies

HTTP is a stateless protocol, so how does one have persistent variables associated with a user?  Cookies of course!  An HTTP cookie (also known simply as a cookie) is used for a website to have state information.  Cookies are great for authentication, shopping carts, and other session variables.

Usually, cookies are used server side, but sometimes it's useful to use cookies on the client side with javascript, and that's where jQuery comes in!

Part One, Setting and Getting Cookies

In order to use jQuery cookies, you'll need the jQuery plugin here: http://plugins.jquery.com/project/Cookie.

Using jQuery and the jQuery cookie plugin, it's easy to set a cookie!  All you have to do is:

$.cookie("key", "value");

Then, if we want to get the cookie, we simply type:


Which returns the value of the key.  If the key was not set, it returns null. Now, to delete a cookie, set it to null and set its expiration date to a negative time:

$.cookie("key", null, {expires : -10});

It's just that easy!  For more info, check out: http://www.electrictoolbox.com/jquery-cookies/.

Part Two, Checking If Cookies Are Enabled

Being able to set, get and delete cookies is all well and good, but what if the client has disabled cookies?  Sometimes it's important to check if the user has cookies enabled so that we as developers can provide the best user experience.  An easy way to check is by setting a cookie and seeing if we can get it:

$.cookie("test", "true");
if ($.cookie("test")) {
  // Cookies are enabled
} else {
  // Cookies are not enabled

For more information regarding checking if cookies are enabled, check out: http://blog.nickburwell.com/2009/05/check-if-cookies-are-enabled-on-client.html


Post a Comment