Archive for January, 2010

Cookie jQuery Plugin

4

As published on my last post, JSON gives us the great possibility to save objects on Cookies. I have already created a JSON Plugin for jQuery, then, why not create one Cookie Plugin that, in conjunction with the JSON plugin, allows us to save objects on cookies? Well, the challenge was simple and I decided to do it for those using jQuery.

The code

Remember than this plugin works in conjunction with my JSON jQuery Plugin, also on this blog.

jQuery.cookie = {
set : function(name,value,options){
options = $.extend({}, options);
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
value = options.json ? encodeURIComponent($.JSON.encode(value)):encodeURIComponent(value);
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', value, expires, path, domain, secure].join('');
},
get : function(name,json){
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = json ? $.JSON.decode(decodeURIComponent(cookie.substring(name.length + 1))):decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
unset: function(name){
this.set(name,'',-1);
}
};

How to use

Note that you have to insert the jquery library on your head section and also the JSON jQuery Plugin -they are all included into the zip file below. Please, also refer to the example provided on my last article ‘cookies on roids’ to view more cookie options.

var obj = {json:'this is a test json property',xml:'this is a test xml property'};
var arr = ['A','B of 2 index array','C','D'];
var str = 'This is a string test';
var num = 123;
$.cookie.set('testobject',obj,{json:true});
$.cookie.set('testarray',arr,{json:true});
$.cookie.set('teststring',str);
$.cookie.set('testnumber',num);
var a = $.cookie.get('testobject',true);
var b = $.cookie.get('testarray',true);
var c = $.cookie.get('teststring');
var d = $.cookie.get('testnumber');
$.cookie.unset('testobject');
$.cookie.unset('testarray');
$.cookie.unset('teststring');
$.cookie.unset('testnumber');
alert('object:'+a.xml);
alert('array:'+b[1]);
alert('string:'+c);
alert('number:'+d);

DOWNLOAD
The zip file includes the JSON jQuery Plugin and Cookie jQuery Plugin together with an example page on how to use them.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: jQuery Cookie Plugin (23.84KB)
added: 02/01/2010
clicks: 1710
Tweet this!Tweet this!
 

Cookies on Roids -JSON Based

2

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 &lt; 10 ? &quot;0&quot; + n : n;<br />
    },<br />
    m : {<br />
        &quot;\b&quot;: '\\b',<br />
        &quot;\t&quot;: '\\t',<br />
        &quot;\n&quot;: '\\n',<br />
        &quot;\f&quot;: '\\f',<br />
        &quot;\r&quot;: '\\r',<br />
        '&quot;' : '\\&quot;',<br />
        &quot;\\&quot;: '\\\\'<br />
    },<br />
    encodeString : function(s){<br />
        if (/[&quot;\\\x00-\x1f]/.test(s)) {<br />
            return '&quot;' + s.replace(/([\x00-\x1f\\&quot;])/g, function(a, b) {<br />
                var c = m[b];<br />
                if(c){<br />
                    return c;<br />
                }<br />
                c = b.charCodeAt();<br />
                return &quot;\\u00&quot; +<br />
                    Math.floor(c / 16).toString(16) +<br />
                    (c % 16).toString(16);<br />
            }) + '&quot;';<br />
        }<br />
        return '&quot;' + s + '&quot;';<br />
    },<br />
    encodeArray : function(o){<br />
        var a = [&quot;[&quot;], b, i, l = o.length, v;<br />
            for (i = 0; i &lt; l; i += 1) {<br />
                v = o[i];<br />
                switch (typeof v) {<br />
                    case &quot;undefined&quot;:<br />
                    case &quot;function&quot;:<br />
                    case &quot;unknown&quot;:<br />
                        break;<br />
                    default:<br />
                        if (b) {<br />
                            a.push(',');<br />
                        }<br />
                        a.push(v === null ? &quot;null&quot; : JSON.encode(v));<br />
                        b = true;<br />
                }<br />
            }<br />
            a.push(&quot;]&quot;);<br />
            return a.join(&quot;&quot;);<br />
    },<br />
    encodeDate : function(o){<br />
        return '&quot;' + o.getFullYear() + &quot;-&quot; +<br />
                pad(o.getMonth() + 1) + &quot;-&quot; +<br />
                pad(o.getDate()) + &quot;T&quot; +<br />
                pad(o.getHours()) + &quot;:&quot; +<br />
                pad(o.getMinutes()) + &quot;:&quot; +<br />
                pad(o.getSeconds()) + '&quot;';<br />
    },<br />
    encode : function(o){<br />
        if(typeof o == &quot;undefined&quot; || o === null){<br />
            return &quot;null&quot;;<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 == &quot;string&quot;){<br />
            return JSON.encodeString(o);<br />
        }else if(typeof o == &quot;number&quot;){<br />
            return isFinite(o) ? String(o) : &quot;null&quot;;<br />
        }else if(typeof o == &quot;boolean&quot;){<br />
            return String(o);<br />
        }else {<br />
            var a = [&quot;{&quot;], 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 &quot;undefined&quot;:<br />
                    case &quot;function&quot;:<br />
                    case &quot;unknown&quot;:<br />
                        break;<br />
                    default:<br />
                        if(b){<br />
                            a.push(',');<br />
                        }<br />
                        a.push(JSON.encode(i), &quot;:&quot;,<br />
                                v === null ? &quot;null&quot; : JSON.encode(v));<br />
                        b = true;<br />
                    }<br />
                }<br />
            }<br />
            a.push(&quot;}&quot;);<br />
            return a.join(&quot;&quot;);<br />
        }<br />
    },<br />
    decode : function(json){<br />
        return eval(&quot;(&quot; + 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 &amp;&amp; (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 &amp;&amp; document.cookie != '') {<br />
            var cookies = document.cookie.split(';');<br />
            for (var i = 0; i &lt; 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 || &quot;&quot;).replace( /^\s+|\s+$/g, &quot;&quot; );<br />
	},<br />
	extend: function()<br />
	{<br />
		var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;<br />
		if ( typeof target === &quot;boolean&quot; ) {<br />
			deep = target;<br />
			target = arguments[1] || {};<br />
			i = 2;<br />
		}<br />
		if ( typeof target !== &quot;object&quot; &amp;&amp; !isFunction(target) )<br />
			target = {};<br />
		if ( length == i ) {<br />
			target = this;<br />
			--i;<br />
		}<br />
		for ( ; i &lt; 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 &amp;&amp; copy &amp;&amp; typeof copy === &quot;object&quot; &amp;&amp; !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) === &quot;[object Function]&quot;;<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

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: Cookies on Roids (2.18KB)
added: 01/01/2010
clicks: 774



Tweet this!Tweet this!
Go to Top