Programming Web with PHP, CSS, Javascript and ∞
Cookies on Roids -JSON Based
Every Web programmer, one day or another, works with cookies. Some of us prefer to use server side cookies, others client cookies, and also both, client and server cookies. On my older blogspot blog, one that I even really care to update everyday as I do with this one, 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!) encoding we could save objects and arrays of information into our good friends ‘cookies’.
Well, on my last post, I have included a JSON Plugin script to use with JQuery. By making a couple of modifications I have created a Cookie and JSON javascript objects to provide you with the possibility to save objects and arrays on cookies. Both of the objects do not require any other dependency library…
Here is the script:
<br />
var JSON = {<br />
useHasOwn : ({}.hasOwnProperty ? true : false),<br />
pad : function(n) {<br />
return n < 10 ? "0" + n : n;<br />
},<br />
m : {<br />
"\b": '\\b',<br />
"\t": '\\t',<br />
"\n": '\\n',<br />
"\f": '\\f',<br />
"\r": '\\r',<br />
'"' : '\\"',<br />
"\\": '\\\\'<br />
},<br />
encodeString : function(s){<br />
if (/["\\\x00-\x1f]/.test(s)) {<br />
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {<br />
var c = m[b];<br />
if(c){<br />
return c;<br />
}<br />
c = b.charCodeAt();<br />
return "\\u00" +<br />
Math.floor(c / 16).toString(16) +<br />
(c % 16).toString(16);<br />
}) + '"';<br />
}<br />
return '"' + s + '"';<br />
},<br />
encodeArray : function(o){<br />
var a = ["["], b, i, l = o.length, v;<br />
for (i = 0; i < l; i += 1) {<br />
v = o[i];<br />
switch (typeof v) {<br />
case "undefined":<br />
case "function":<br />
case "unknown":<br />
break;<br />
default:<br />
if (b) {<br />
a.push(',');<br />
}<br />
a.push(v === null ? "null" : JSON.encode(v));<br />
b = true;<br />
}<br />
}<br />
a.push("]");<br />
return a.join("");<br />
},<br />
encodeDate : function(o){<br />
return '"' + o.getFullYear() + "-" +<br />
pad(o.getMonth() + 1) + "-" +<br />
pad(o.getDate()) + "T" +<br />
pad(o.getHours()) + ":" +<br />
pad(o.getMinutes()) + ":" +<br />
pad(o.getSeconds()) + '"';<br />
},<br />
encode : function(o){<br />
if(typeof o == "undefined" || o === null){<br />
return "null";<br />
}else if(o instanceof Array){<br />
return JSON.encodeArray(o);<br />
}else if(o instanceof Date){<br />
return JSON.encodeDate(o);<br />
}else if(typeof o == "string"){<br />
return JSON.encodeString(o);<br />
}else if(typeof o == "number"){<br />
return isFinite(o) ? String(o) : "null";<br />
}else if(typeof o == "boolean"){<br />
return String(o);<br />
}else {<br />
var a = ["{"], b, i, v;<br />
for (i in o) {<br />
if(!JSON.useHasOwn || o.hasOwnProperty(i)) {<br />
v = o[i];<br />
switch (typeof v) {<br />
case "undefined":<br />
case "function":<br />
case "unknown":<br />
break;<br />
default:<br />
if(b){<br />
a.push(',');<br />
}<br />
a.push(JSON.encode(i), ":",<br />
v === null ? "null" : JSON.encode(v));<br />
b = true;<br />
}<br />
}<br />
}<br />
a.push("}");<br />
return a.join("");<br />
}<br />
},<br />
decode : function(json){<br />
return eval("(" + json + ')');<br />
}<br />
};</p>
<p>var Cookie = {<br />
jsonencode : JSON.encode,<br />
jsondecode : JSON.decode,</p>
<p> set : function(name,value,options){</p>
<p> options = this.extend({}, options);</p>
<p> if (value === null) {<br />
value = '';<br />
options.expires = -1;<br />
}<br />
var expires = '';<br />
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {<br />
var date;<br />
if (typeof options.expires == 'number') {<br />
date = new Date();<br />
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));<br />
} else {<br />
date = options.expires;<br />
}<br />
expires = '; expires=' + date.toUTCString();<br />
}</p>
<p> var self = this;</p>
<p> value = options.json ? encodeURIComponent(Cookie.jsonencode(value)):encodeURIComponent(value);</p>
<p> var path = options.path ? '; path=' + (options.path) : '';<br />
var domain = options.domain ? '; domain=' + (options.domain) : '';<br />
var secure = options.secure ? '; secure' : '';</p>
<p> document.cookie = [name, '=', value, expires, path, domain, secure].join('');<br />
},<br />
get : function(name,json){</p>
<p> var cookieValue = null;</p>
<p> if (document.cookie && document.cookie != '') {<br />
var cookies = document.cookie.split(';');<br />
for (var i = 0; i < cookies.length; i++) {<br />
var cookie = this.trim(cookies[i]);<br />
// Does this cookie string begin with the name we want?<br />
if (cookie.substring(0, name.length + 1) == (name + '=')) {<br />
cookieValue = json ? this.jsondecode(decodeURIComponent(cookie.substring(name.length + 1))):decodeURIComponent(cookie.substring(name.length + 1));<br />
break;<br />
}<br />
}<br />
}</p>
<p> return cookieValue;</p>
<p> },<br />
unset: function(name){<br />
Cookie.set(name,'',-1);<br />
},<br />
trim: function( val ) {<br />
return (val || "").replace( /^\s+|\s+$/g, "" );<br />
},<br />
extend: function()<br />
{<br />
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;<br />
if ( typeof target === "boolean" ) {<br />
deep = target;<br />
target = arguments[1] || {};<br />
i = 2;<br />
}<br />
if ( typeof target !== "object" && !isFunction(target) )<br />
target = {};<br />
if ( length == i ) {<br />
target = this;<br />
--i;<br />
}<br />
for ( ; i < length; i++ )<br />
if ( (options = arguments[ i ]) != null )<br />
for ( var name in options ) {<br />
var src = target[ name ], copy = options[ name ];</p>
<p> if ( target === copy )<br />
continue;</p>
<p> if ( deep && copy && typeof copy === "object" && !copy.nodeType )<br />
target[ name ] = this.extend( deep,<br />
src || ( copy.length != null ? [ ] : { } )<br />
, copy );</p>
<p> else if ( copy !== undefined )<br />
target[ name ] = copy;</p>
<p> }<br />
return target;<br />
},<br />
isFunction: function(obj){<br />
return toString.call(obj) === "[object Function]";<br />
}<br />
};<br />
As you can see above, I have included a couple of methods that allow me to extend the options of the object at will (thanks jQuery). I believe that you will find it quite useful to extend its functionality. Any ideas will be highly appreciated.
How to use it
</p>
<p>// Create a cookie with the given name and value and other optional parameters.<br />
//<br />
// session cookie -no json<br />
Cookie.set('the_cookie_name', 'the_value');</p>
<p>// get cookie (no json):<br />
var cv = Cookie.get('the_cookie_name');</p>
<p>// session cookie -json, the value can be an object or an array too<br />
Cookie.set('the_cookie_name', 'the_value', {json:true});</p>
<p>// get the cookie (json)<br />
var cv = Cookie.get('the_cookie_name',true);</p>
<p>// Secured cookie, expiring in 14 days<br />
Cookie.set('the_cookie_name', 'the_value', { expires: 14, path: '/', domain: 'yourdomain.com', secure: true });</p>
<p>// Deleting a cookie<br />
Cookie.unset('the_cookie_name', null);</p>
<p>
DOWNLOAD
|
|
download: Cookies on Roids (2.18KB) added: 01/01/2010 clicks: 233 description: |
| Print article | This entry was posted by Antonio Ramirez on January 1, 2010 at 2:13 pm, and is filed under Javascript, Tools. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |







I'm a 38 year old Web Developer working from Ibiza, Balearic Islands, Spain. I am Founder and Lead Developer for