Javascript

Javascript Archives

 

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!
 

JSON jQuery Plugin

14

I finally got a bit of time and I started playing around with the creation of jQuery plugins and did created a couple of them that I believe all of you will find useful, one of them is a JSON plugin.

As you all know jQuery do not have a JSON encode function. I truly do not know the reason why but to implement it was quite easy -maybe the guys from jQuery thought that it wasn’t really necessary and I agree with them. Most of us use JSON on the server side through PHP or whatever the server tech we use but sometimes, and I repeat, sometimes, we require to develop client applications that by using JSON (thanks David Crockford) we can reduce our server resources and the amount of data transmitted between client and server. But this is a subject that I will treat in the next posts.

Here is the plugin code:

jQuery.JSON = {
useHasOwn : ({}.hasOwnProperty ? true : false),
pad : function(n) {
return n < 10 ? "0" + n : n;
},
m : {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
},
encodeString : function(s){
if (/["\\\x00-\x1f]/.test(s)) {
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + s + '"';
},
encodeArray : function(o){
var a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null" : this.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
},
encodeDate : function(o){
return '"' + o.getFullYear() + "-" +
pad(o.getMonth() + 1) + "-" +
pad(o.getDate()) + "T" +
pad(o.getHours()) + ":" +
pad(o.getMinutes()) + ":" +
pad(o.getSeconds()) + '"';
},
encode : function(o){
if(typeof o == "undefined" || o === null){
return "null";
}else if(o instanceof Array){
return this.encodeArray(o);
}else if(o instanceof Date){
return this.encodeDate(o);
}else if(typeof o == "string"){
return this.encodeString(o);
}else if(typeof o == "number"){
return isFinite(o) ? String(o) : "null";
}else if(typeof o == "boolean"){
return String(o);
}else {
var self = this;
var a = ["{"], b, i, v;
for (i in o) {
if(!this.useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(b){
a.push(',');
}
a.push(self.encode(i), ":",
v === null ? "null" : self.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
},
decode : function(json){
return eval("(" + json + ')');
}
};

How to use

Copy and paste the above code onto a file and name it whatever you like, for the sake of the example we will call it jquery.json.js. And then configure your head section like this:

<!-- jquery library (if you dont have it, then download it :)  -->
<script language="javascript" src="jquery.1.3.2.js" ></script>
<!-- our plugin file -->
<script language="javascript" src="jquery.json.js"></script>

That’s it, now we can call our plugin like this:

// test variables
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'];
// encoding an object
var a = $.JSON.encode(obj);
alert('json encoded object:'+a);
// decoding an object
var b = $.JSON.decode(a);
alert('json decoded object property:'+b.json);
// encoding an array
a = $.JSON.encode(arr);
alert('json encoded array:'+a);
// decoding the array
b = $.JSON.decode(a);
alert('json decoded array:'+b[1]);

On future posts we will make use of this plugin to show what we can do with it.

Tweet this!Tweet this!
autocomplete

Ajax Powered Autocomplete Plugin for JQuery.js

3

I am glad to announce the launch of the successfull Ajax Powered Autocomplete for Prototype.js now as a plugin for JQuery. No much to say… if any of you want to have a look at this piece of code you can check it here.

Any feedback is highly appreciated.



Tweet this!Tweet this!
 

Javascript Online Compression Tools

0

Picture 9When a Web project is finished, it is time to think how to make it better, faster… how to improve user’s experience. One of the most important things is javascript code compression in order to speed up page downloads and there are a couple of tools around that allows us to do it.

I just include three references:

The Online YUI Compressors

These tools allows us to make use of the famous Yahoo Javascript Compression algorithm. Both of the above references does the same results, there is only a major difference between both: whilst the one created by Mike allows you to paste your script or upload a file to compress, the one created by Rodolphe Stoclin only allows us to upload the file to compress.

The Online Javascript Minifier

This tool can reduce our code by using two different algorithms: the JSMin by David Crockford and the Packer method by Dean Edwards.

Which One to Use?

I personally like those algorithms that do not make any use of the eval function and doesn’t change much the code I program, test, and implement. I think that will only depend of the developer choice.

There is an online tool that help us compare the algorithms. If that helps you to decide which one to use: http://compressorrater.thruhere.net/



Tweet this!Tweet this!
Go to Top