J is for jCookies – HTTP Cookie Handling for jQuery

jCookies, a jQuery plugin, makes getting and settings HTTP Cookies a breeze. jCookies allows the storage of any type of data: strings, arrays, objects, etc. A while back while developing my FormBuilder I needed a good solution for storing cookies via JavaScript. As a result of the work down for that project I built jCookies.

jCookies, a jQuery plugin, makes getting and settings HTTP Cookies a breeze. jCookies allows the storage of any type of data: strings, arrays, objects, etc. A while back while developing my FormBuilder I needed a good solution for storing cookies via JavaScript. As a result of the work down for that project I built jCookies.

The following will demonstrate the methods for storing and retrieving data using jCookies and will show how to retrieve data using server side code such as C# and PHP.

Note: Data is stored in the cookie as JSON data then Base64 encoded to enable the survival through transport layers that are not 8-bit clean. JSON and base64 functions are included in the script and if trimmed out, provided they exist elsewhere, would reduce the size by 70%.

Creating Cookies

To create a cookie you call jCookies and must pass two properties, name and value.

$.jCookies({
    name : 'Listening To',
    value : { album : 'The Go Round', artist : 'Inf', rating : 9, thumbs_up : true}
});

As you can see you can store pretty much anything. By default cookies are set to expire after 27 days. You can edit the expiration by settings one of the following properties: seconds, minutes, hours, days. The value entered for these properties must be a valid number or they will be ignored.

$.jCookies({ name : 'User', value : { username : 'Bob' , level : 5 }, minutes : 60 });

Note: If you plan on retrieving data from the server side via ASP.net keep the cookie data very simple. More on this later.

Retrieving Cookies

To retrieve a cookie you call jCookies and pass a single properties, get.

var listening_to = $.jCookies({ get : 'Listening To' });
    // response: { album : 'The Go Round', artist : 'Inf', rating : 9, thumbs_up : true}

var rutabaga = $.jCookies({ get : 'Rutabaga' }); // (cookie was set by another proces)
    // response: false

Data is returned just as you would expect it to. If there was no cookie stored with that name, the cookie has expired, or there was an error then the response would be false. If you want to see if there was an error with the cookie you can set the optional property error. By default this property is set to false.

var rutabaga = $.jCookies({ get : 'Rutabaga', error : true });
    /* response:
        Error : {
            arguments : undefined,
            message : "Invalid base64 data",
            stack : "—",
            type : undefined
        }
    */

This is an error response from Chrome. Depending on your browser your results may vary.

Erasing Cookies

To erase a cookie you call jCookies and pass a single property, erase.

var erased_listening_to = $.jCookies({ erase : 'Listening To' });
    // response: true

var rutabaga = $.jCookies({ erase : 'Rutabaga' });
    // response: false

If a cookie existed and was erased successfully true is returned. If the cookie never existed false is returned.

jCookies Server Side

Dealing with HTTP Cookies created by jCookies on the server side is a cinch you simply need to Base64 decode the data then JSON decode the data.

Setting cookie in JavaScript

$.jCookies({name:'user',value:{name:'brian',level:'awesome'}});
    // response: true

Retrieving the cookie in PHP

<?php print_r(json_decode(base64_decode($_COOKIE['user'], true))); ?>
    /* response:
        stdClass Object
            (
            [name] => brian
            [level] => awesome
            )
    */

With PHP it couldn’t be easier. In the demonstration above I am printing out the entire cookie.

Retrieving the cookie in C#

Dictionary<string,object> user =
  new JavaScriptSerializer().Deserialize<Dictionary<string,object>>
  (Encoding.UTF8.GetString(
	Convert.FromBase64String(Page.Request.Cookies["user"].Value)
  ));

Page.Response.Write("user : name  = " + (string) user["name"]);

With C# its a bit more difficult. You have to set the type of each bit of data that comes back before you can use it. That is why I am storing the data as Dictionary<string,object>. We set the property to string to make it accessible and set the value to object for casting later. If you knew exactly the format of the cookie beforehand you could always create your own class and store that data in that class.

That about does it. If you want to know more visit my site or the jQuery plugin page.

Download jCookies

Tagged with:

Brian S. Reed

Brian S. Reed works full time for his local municipality and as a freelance web designer and developer with a passion for clean simple code. He works on many different types of projects from SharePoint to WordPress. Contact him on his website, or IM: iambriansreed.

Stay up to date with the latest web design and development news and relevant updates from Codrops.

Feedback 9

Comments are closed.
  1. Can you use it to check a certain cookie for a certain value? And then do something, based on that?