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.
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, provided they exist elsewhere, out 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 to a minimum. More on this later.
top
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 process)
// 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.
top
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.
top
jCookies Server Side
Dealing with HTTP Cookies created by jCookies 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>json =
new JavaScriptSerializer().Deserialize<Dictionary<string,object>>(
Encoding.UTF8.GetString(
Convert.FromBase64String(Page.Request.Cookies["user"].Value)
)
);
Page.Response.Write("user = " + (string) json["name"]);
// response: user = brian
With C# its a bit more difficult. You have to type each bit of data that comes back before you can use it. That is why I am storing the data as Dictionary. We set the property to string to make it accessible and leave the value open 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.
top
Download
For the latest release, changelog, and other info please visit the official jQuery plugin site.
top
FAQ
- Q: How can I contact you?
- A: E-mail, Phone, Chat, Smoke Signals, Carrier Pigeons..
- Q: Will you implement a feature if I donate a specified amount?
- A: I will be happy to do a custom installation and create additional features; contact me.