jQuery cookieJar

Dan G. Switzer, II wrote here pointing out there are some important things to be taken into consideration while using cookies and this plugin.
1) Cookies are sent with each request header.
2) The total Cookie size per domain is generally 4K (which is per the spec http://www.ietf.org/rfc/rfc2109.txt.) This is not a per Cookie limit, but a total name-value pair.

Introduction

I’m writing a tablesorter 2.0 plugin which I will release here shortly, along with tutorial. The plugin allows the sort order of the table to be stored in a cookie, which is then restored upon a table of the same id loading.

I had the need to store multiple values in a single cookie, it would be crazy to store each tables value in a separate cookie. So I started looking for a solution and couldn’t really find a easy one to use, and nothing for jQuery but cookie which can only store a single value in cookies. Ajaxian revealed that CookieJar: JSON Cookies by Lalit Patel existed a great idea of storing a JSON encoded object as the cookie value. It seems that this has already been implemented into Mootools. I suddenly felt the need to create a jQuery plugin.

Requirements

Compatibility

So far the plugin has been tested in windows using the following browsers.

Usage

Javascript - Simple set, get

1
2
3
var myCookieJar = $.cookieJar('myCookieJar');
myCookieJar.set('test1', 'hello world');
alert(myCookieJar.get('test1'));

Javascript - Chained set, get

1
2
$.cookieJar('myCookieJar').set('test1', 'hello world');
alert($.cookieJar('myCookieJar').get('test1'));

Javascript - Larger Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
jQuery(function($) {
    // load the cookieJar into an object
    var accessCookie = $.cookieJar('accessInfo');
 
    // get the name from the cookieJar
    var name = accessCookie.get('name');
 
    // check that the name is defined
    if (typeof name == 'undefined') {
        // name was undefined, prompt for a name
        var name = prompt('Your name please');
        // store the name in the cookieJar
        accessCookie.set('name', name);
    }
 
    // show the name from the cookieJar on in tag with
    // id access-name
    $('#access-name').text(accessCookie.get('name'));
 
    // get the accessLog from the cookieJar
    var accessLog = accessCookie.get('accessLog');
 
    // check the that accessLog is an Array object
    if (typeof accessLog != 'object' || accessLog.constructor != Array) {
        // accessLog wasn't an Array object, set it as an Arrray object
        var accessLog = [];
    }
 
    // add the current date as a string to the begining
    // of the accessLog Array
    accessLog.unshift(new Date().toString());
 
    // store the accessLog Array in the cookieJar
    accessCookie.set('accessLog', accessLog);
 
    // loop though all the elements in the Array object accessLog
    $.each(accessLog, function(index, value) {
        // append the value to the unordered list
        $('#access-log ul').append('<li>'+value+'</li>');
    });
 
    // show the cookieJar JSON encoded string
    $('#cookie-contents').text(accessCookie.toString());
});

Documentation

You’ll find most of the code documented.
But here is an outline of the methods.

cookieJar.construct(name, [object options) object
Not usually directly called, just use “var myCookieJar = jQuery.cookieJar(’name’, myOptions)”
options object
bool debug
To show debug logging, default false
bool cacheCookie
To not reload the cookie on each get, default true.
string cookiePrefix
Stops the name of cookieJars clashing with any other cookies, default ‘jqCookieJar_’
object cookie
Any options that you want to pass to the cookie plugin, default { path: ‘/’, expires: 365 }
cookieJar.set(string name, value) bool
Sets a value in the cookie jar using a name to identify it
cookieJar.get(string name) mixed
Gets a value from the cookie jar using a name to identify it
cookieJar.remove([string name]) bool
Removes a value from the cookie jar using a name to identify it No name will clear the cookie jar of all values
cookieJar.setFromObject(object object) bool
Uses the object as the set of values to store in the cookie jar
cookieJar.toObject() object
Returns the contents of the cookie jar as an object
cookieJar.toString() string
Returns the contents of the cookie jar as a JSON encoded string
cookieJar.destroy() bool
Removes the cookie containing the cookie jar from the server

Note: The cookieJar is loaded and cached upon construct. Once the cookie jar is loaded it doesn’t reread the cookie again. This can be disabled via the options see cacheCookie.

Downloads

jquery.cookiejar.example.html
jquery.cookiejar.js (6.54 KB)
jquery.cookiejar.pack.js (2.06 KB)
jquery.json.js
jquery.cookie.js

Comments

10 Responses to “jQuery cookieJar”

  1. Travis Phipps on August 13th, 2007 3:00 pm

    I LOVE IT! I’ve been putting off writing my own plugin that would do the tablesorter cookie stuff you’re talking about. I’m so glad I waited so you could write it for me!! :)

    I’ll definitely be keeping a lookout for your release. Thank you, thank you, thank you!

    And more to the point: This plugin looks great as well.

  2. Adrian on August 30th, 2007 7:11 am

    Is your plugin supporting updating an array cookie ?
    Let’s say I have a cookie with user[full_name], user[email] and user[website] and I want to update just one of the elements (eg: user[email]). How can I do that?

  3. letssurf on August 30th, 2007 9:10 am

    I think I understand what you are saying. If so you would create a cookieJar named user then save the elements.

    e.g.

    jQuery(function($) {
      /* create or load the cookieJar */
      var userCookie = $.cookieJar('user');
     
      /* save some info */
      userCookie.set('full_name', 'Users Fullname');
      userCookie.set('email', 'joe@bloggs.com');
      userCookie.set('website', 'http://www.google.com/');
     
      /* do other stuff */
     
      /* change the email address stored */
      userCookie.set('email', 'joe2@bloggs.com');
    });
  4. jQuery serverCookieJar : jDempster.com on September 14th, 2007 12:13 pm

    […] plugin is designed as an alternative to cookieJar. See it’s doc’s and usage […]

  5. Stanley C. Lemon on September 24th, 2007 3:38 pm

    Greetings,
    This was a great joy to find this afternoon. It would be nice to see this merge with the cookie plugin and then to possibly even work its way into the core. This plugin is so useful on so many levels.

    FWIW, depending on the server side language being used and what exactly you want to do with the cookies, setting can be done in PHP for array values, ie:

    $.cookie('varname[property]', value);

    PHP parses that correctly, however for whatever reason in this particular car just [] does not work.

    Anyhow, thanks again for the plugin!

    Pax,
    - Stan

  6. dave on May 16th, 2008 1:45 am

    Hi & thanks for the great code, extremely useful…
    I have one problem, I am using cookies to hide certain divs on page load.
    All divs are shown on first page load by default, then if a div title is clicked a cookie is added.
    When I use:
    alert ($.cookieJar(’CookieJar’).toString());
    I get a result like:
    {”box5″:”closed”,”box9″:”closed”}
    Can you tell me how I would now close these boxes on page load?
    Currently I am using the following script inside a php loop so it gets executed on every box displayed but I want to reduce the code to just executing once,
    any help is well appreciated.

    $(document).ready(function(){
    if ($.cookieJar(’zcCookieJar’).get(”)) {
    $(”# .Content”).hide();
    }
    });

  7. letssurf on May 16th, 2008 10:47 am

    Try this

    jQuery(function($) {
    	var cookieJar = $.cookieJar('CookieJar');
    	$.each(cookieJar.toObject(), function(i, val) {
    	    if (val == 'closed') {
    	        $('#'+i).hide();
    	    }
    	});
    });
  8. dave on May 16th, 2008 2:27 pm

    That works perfectly, Thank you…

  9. John on June 12th, 2008 7:40 pm

    This looks great, one (probably stupid) question. How would I set a cookie with a link? For instance ‘click here to set cookie’. I want to have links where customers can find out more about products, then when they are ready can go to a contact form and all the products from the cookiejar are auto filled into the comment form. I think I see how to load the cookies into the form but not sure what code I use to ‘choose’ product. Thanks for the great code.

  10. lalit.lab » Blog Archive » Cookie Jar: Yummy JSON Cookies (using Prototype) on June 15th, 2008 8:31 am

    […] jQuery port […]

Leave a Reply