Cookie Jar: Yummy JSON Cookies (using Prototype)
on Thursday, April 12th, 2007 at 12:39 pmJavaScript code to store data as JSON strings in cookies. It uses prototype.js to store and retrieve JSON data from cookies.
Now we can store and retrieve JavaScript Objects, Arrays, Boolean, String, Number values using cookies, just like storing Java Objects in session on the server side.
Works with Firefox 1.5, 2.0, IE 6.0 and Opera 9.10.
Example
(Execute this example)
jar = new CookieJar({ expires:3600, // seconds path: '/' }); dog = {name: 'Jacky', breed: 'Alsatian', age:5}; jar.put('mydog', dog); mydog = jar.get('mydog'); alert("My dog's name is " + mydog.name); alert("He is " + mydog.age + " years old"); alert("He is an " + mydog.breed);
Download
You can view the source code here.
This code is released under CC Attribution-ShareAlike 2.5
This code is released under Apache Software License.
API
CookieJar(options)
Constructor. Takes in a object as options.
options = { expires: '', // time in seconds (defualt: 3600) path: '', // cookie path domain: '', // cookie domain secure: '' // secure ? }
boolean put(string name, mixed value)
Puts a particular cookie in the cookie jar. The cookie is associated with the name. Returns false if cannot add cookie (Ex: max cookie size exceeded!). Returns true on success.
mixed get(string name)
Gets a particular cookie from the cookie jar. Returns null if not found.
boolean remove(string name)
Removes a particular cookie from the cookie jar. Returns true on success, false otherwise.
void empty()
Empties the Cookie Jar.
array getKeys()
Gets array of all the cookie names.
object getPack()
Gets all the cookies as a single JavaScript object (Package) with name value pairs.
Change Log
v 0.5 (26-Jan-09)
- Changed the License to Apache Software License 2.0
v 0.4 (11-Aug-07)
- Removed a extra comma in options (was breaking in IE and Opera). (Thanks Jason)
- Removed the parameter name from the initialize function
- Changed the way expires date was being calculated. (Thanks David)
v 0.3 (22-Jun-07)
- Removed dependancy on json.js (http://www.json.org/json.js)
- empty() function only deletes the cookies set by CookieJar. Leaves alone other cookies like session_id etc.
v 0.2 (12-Apr-07)
- Released for public use.
June 15th, 2008 at 4:33 am
Very nice.
Could you please submit this to http://scripteka.com
Thanks.
June 15th, 2008 at 11:10 am
@kangax:
I already have
Thanks!
July 1st, 2008 at 5:31 am
Hi Lalit, thank for you script. Very nice and clean.
July 6th, 2008 at 4:06 am
Very slick piece of code – I’m developing a couple of applications at the moment where I’m using this – it’s a really clean and well thought out implementation – thanks for sharing it!
July 10th, 2008 at 12:35 pm
Does this support arrays in a json string? I keep getting errors when trying to implement an array in the object.
eg. It stores the following without a problem:
jar.put(’test’,{’alpha’:[{'name':'one'},{'name':'two'},{'name','three'}]})
but when I try to get it (eg. test = jar.get(’test’)), it always returns a string and not an object. So I can’t get the value of test.alpha[0].name.
Am I doing something wrong?
July 10th, 2008 at 12:44 pm
Correction:
jar.put(’test’,{’alpha’:[{’name’:'one’},{’name’:'two’},{’name’:'three’}]})
(but still having problems with it).
July 10th, 2008 at 2:35 pm
Raj, you need to pass the array as a JS object to the function, it will automatically convert it to JSON; and when you do get, it will convert it back to object. You need not pass a JSON encoded string.
July 10th, 2008 at 2:37 pm
Raj,
2nd post should work. I will test and get back to you.
July 11th, 2008 at 6:58 am
Hi Lalit, it seems I was suffering the “invalid label” problem (http://willcode4beer.com/tips.jsp?set=jsonInvalidLabel).
It works a treat now! Thanks!
July 17th, 2008 at 9:10 am
It’s very nice.I like it.
September 6th, 2008 at 6:26 am
LOVE this, thank you! doesn’t seem to work in IE6 tho. But I’m using prototype v1.6 – has there been any update? (does not work in IE7 either)
September 9th, 2008 at 1:29 am
It was my fault this was not working under IE. >_< Sorry for the mis-information.
September 28th, 2008 at 12:11 am
Hi, I’m trying to erase the entire cookie, but I cant. You could check my code?
That created the cookie:
jar = new CookieJar({expires:3600, path: ‘/’});
shop = {order_id: results['order_id']};
jar.put(’shop’, shop);
And with that, in a function, I try to delete the cookie:
jar = new CookieJar();
if (jar.get(’shop’)){
shop = jar.get(’shop’);
if (shop.order_id==results['order_id']){
jar.remove(’shop’);
}
}
Your script its GREAT!!!
October 13th, 2008 at 6:56 am
[...] Store JSON data in cookies – lalit.org [...]
November 28th, 2008 at 7:56 pm
[...] Store JSON data in cookies – lalit.org [...]
February 15th, 2009 at 11:28 pm
Awesome script.
A problem with cookies -that your jar doesnt fix- is, that when you put() you have to reload the entire page before you get() the same value.
I changed so it now keeps track of what you put(), your cookie jar now always returns the value of the cookie as it should be, not how it was before you started changing things.
I did this by using your getPack() function and rewriting the get() method. The original get() is now raw(), and this is my new get:
get: function(name) {
value = this.tempJar[ name ];
if ( value )
return value;
else
return null;
},
You might want to make this as a default functionality. For others; note; you need to make more changes for this to work. One of them is placing
this.tempJar = this.getPack();
in the initialize() method at the end.
February 20th, 2009 at 4:09 pm
Oh, and there is a bug in the cookie_expiration date. getTime() returns time elapesed in miniseconds, not in seconds. This si the correct code:
date = new Date( ( parseInt( date.getTime() / 1000 ) ) + (this.options.expires ) );
March 4th, 2009 at 11:22 pm
Nifty piece of code m8!
Thanks.
March 27th, 2009 at 1:38 pm
Hello! great script. how do i set the cookie to never expire?
March 29th, 2009 at 3:29 am
This is great!
But, I am most likely missing something (i am new to prototype and OO Javascript), but how do I retrieve a cookie, add a new field to it and return it.
So if I had a cookie that contained {item1:”data1″, item2:”data2″}
and I wanted to add {item3:”data3″}
So when I next retrieved the cookie it would give me {item1:”data1″, item2:”data2″, item3:”data3″}
April 10th, 2009 at 2:04 pm
Hi. Nice script. would be nice if we could just access the properties directly and then there was a save / load function.
Can you tell us some rough maximum cookie sizes in your little documentation?
Thanks
April 11th, 2009 at 12:23 am
[...] Store JSON data in cookies – lalit.org [...]
June 15th, 2009 at 3:41 pm
Nice script! Got 2 comments:
When enabling the secure option on a non-https connection, the cookie values will be lost. I changed this line of code to make it work:
if (this.options.secure == ’secure’ && (”https:” == document.location.protocol)) {..
Besides this, when storing a boolean as javascript boolean, and then retrieve it, it results in a string (”true”). This is not really convenient because you have to typecast it.
Thanks anyway, great script.
August 6th, 2009 at 6:19 pm
[...] – bosrup.com PlotKit – JavaScript Chart Plotting – liquidx – liquidx.net Store JSON data in cookies – lalit.org Sorted tables – friedcellcollective.net TableKit – millstream.com [...]
October 13th, 2009 at 9:28 am
Is great, very good.
October 18th, 2009 at 9:06 pm
[...] Cookie Jar [...]
January 2nd, 2010 at 2:44 am
[...] I post one class to work with cookies on the client side and one fellow programmer told me about json cookies. I thought it was a great script and that was because by using JSON (thanks David Crockford again!) [...]
January 5th, 2010 at 10:39 am
[...] Store JSON data in cookies – lalit.org [...]
January 5th, 2010 at 4:15 pm
[...] tools for specific requirements XML.ObjTree XML parser, jsvalidate, Form validation, Store json data in cookies, Livepipe Tabs, BSN AutoSuggest, BarelyFitz Tabs, overLIB Tooltips, Kryogenix Sortable tables, FD [...]
January 26th, 2010 at 2:47 pm
Can’t get the empty() method to work, more examples would be nice, or at least one example of each method).
February 13th, 2010 at 5:33 am
document.cookie.match(name + ‘=(.*?)(;|$)’) in get function returns null in ie7 and ie8 — it works perfectly with FF