Posts tagged Javascript

 

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: 770



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!
 

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!
 

Ajax Load -Ajax Loading GIF Generator

0

Ajax Load - AJax Loading GIF GeneratorWho of those of you that use ajax on your projects aren’t looking around the web to find the perfect ‘loading please wait’ GIF for your brand new web application or site? I have to confess that I was one of them. I am not a designer, I can program any web application in a matter of days but when it comes to design… puff… It is the reason why I am always crawling the web for ‘inspiration’.

One of those days crawling I found an online tool created by kath called Ajax Load – Ajax Loading GIF Generator. There you don’t need to worry if you know how to design or not, this simple but very useful tool allows you to select the type of design you want for your ajax loading gif, the foreground and background colors and voilá, your ajax loading gif is ready to download.

Dropdown List

For those, like me, without a clue about designing there it is, the Ajax Load – Ajax Loading GIF Generator.



Tweet this!Tweet this!
 

Image Gallery via Ajax using JQuery Tools

8

overlayThe other day I was having a bit of headache trying to find the best way to display a gallery via Ajax for one of my projects. There are tons of great lightbox type scripts out there (I even have one: lightboxXL) but none of them truly suit my needs as most of them, including mine, are creating the image galleries on DOM load, or on Document load, or on Window load… none of them allowed me to make use of Ajax and I certainly didn’t want to rewrite the code of anybody.

Suddenly, searching the web I found the OVERLAY object from JQuery Tools. This library offers a set of objects that extend the functionality of JQuery, it contains six of the most useful JavaScript tools available for today’s website. The beauty of this library is that all of these tools can be used together, extended, configured and styled. In the end, you can have hundreds of different widgets and new personal ways of using the library.

This is how I used it to create the Image Gallery via Ajax:

Insertion of Libraries

First we must include the library on the HEAD section of the page (JQuery Tools have a compressed version of its tools and latest version of JQuery library)

<!-- Full version of jQuery Tools + jQuery 1.3.2 -->
<script type="text/javascript" src="js/jquery.tools.min.js"></script>

CSS Coding

This is where we are going to apply styles to our overlay.

/* scrollable should not disable gallery navigation */
#gallery .disabled {
    visibility:visible !important;
}
#gallery .inactive {
    visibility:hidden !important;
}
/* the overlayed element */
.simple_overlay {
    /* must be initially hidden */
    display:none;
    /* place overlay on top of other elements */
    z-index:10000;
    /* styling */
    background-color:#333;
    width:675px;
    min-height:200px;
    border:1px solid #666;
    /* CSS3 styling for latest browsers */
    -moz-box-shadow:0 0 90px 5px #000;
    -webkit-box-shadow: 0 0 90px #000;
}
/* close button positioned on upper right corner */
.simple_overlay .close {
    background-image:url(images/overlay/close.png);
    position:absolute;
    right:-15px;
    top:-15px;
    cursor:pointer;
    height:35px;
    width:35px;
}
/* styling for elements inside overlay */
.simple_overlay .details {
    position:absolute;
    top:15px;
    right:15px;
    font-size:11px;
    color:#fff;
    width:150px;
}
.simple_overlay .details h3 {
    color:#aba;
    font-size:15px;
    margin:0 0 -10px 0;
}
/* "next image" and "prev image" links */
.next, .prev {
	/* absolute positioning relative to the overlay */
	position:absolute;
	top:40%;
	border:1px solid #666;
	cursor:pointer;
	display:block;
	padding:10px 20px;
	color:#fff;
	font-size:11px;
	/* upcoming CSS3 features */
	-moz-border-radius:5px;
	-webkit-border-radius:5px;
}
.prev {
	left:0;
	border-left:0;
	-moz-border-radius-topleft:0;
	-moz-border-radius-bottomleft:0;
	-webkit-border-bottom-left-radius:0;
	-webkit-border-top-left-radius:0;
}
.next {
	right:0;
	border-right:0;
	-moz-border-radius-topright:0;
	-moz-border-radius-bottomright:0;
	-webkit-border-bottom-right-radius:0;
	-webkit-border-top-right-radius:0;
}
.next:hover, .prev:hover {
	text-decoration:underline;
	background-color:#000;
}
/* when there is no next or previous link available this class is added */
.disabled {
	visibility:hidden;
}
/* the "information box" */
.info {
	position:absolute;
	bottom:0;
	left:0;
	padding:10px 15px;
	color:#fff;
	font-size:11px;
	border-top:1px solid #666;
}
.info strong {
	display:block;
}
/* progress indicator (animated gif). should be initially hidden */
.progress {
	position:absolute;
	top:45%;
	left:50%;
	display:none;
}
/* everybody should know about RGBA colors. */
.next, .prev, .info {
	background:#333 !important;
	background:rgba(0, 0, 0, 0.6) url(images/h80.png) repeat-x;
}

HTML Coding

Now the HTML holder

<!-- overlay element -->
<div class="simple_overlay" id="gallery">
<!-- "previous image" action -->
<a class="prev">prev</a>
<!-- "next image" action -->
<a class="next">next</a>
<!-- image information -->
<div class="info"></div>
<!-- load indicator (animated gif) -->
<img class="progress" src="images/ajax-loader.gif" />
<!-- end of overlay element -->
</div>

PHP Response

By now, you should already know how to do Ajax calls using JQuery, if you don’t please review it on JQuery’s site. What we are going to check is how is the PHP response in order to make our Image Gallery work after an Ajax call.

// ************************************
// Scenario: An ajax call to this PHP script was done and
// a POST variable has been sent in order to fill $pics from
// a database.
//
// pics == array of pictures
// ************************************
// loop the array
foreach($pics as $pic)
{
	// check the class attribute --> ibox
	// $pic is also an object with certain properties in this case
       $html .= '<div class="pic">
			<a href="'.$pic->imgPath.$pic->strName.'" class="ibox" title="'.$pic->strName.'">
			<img src="'.$pic->imgPath.$pic->strName.'" width="50" border="0" /></a>
			</div>';
}
//
// here I create the necessary javascript code to load the OVERLAY object of JQuery Tools
// please check the 'ibox' call
//
$html .= '
     <script type="text/javascript">
     //<![CDATA[
     $('.ibox').overlay({
    		target: '#gallery',
    		expose: '#f1f1f1'
		}).gallery({
		speed: 800 });
     //]]></script>';
//
// echo response
//
echo $html;

And that’s it, once your image gallery is loaded whereever you wish to from an Ajax call, the latest javascript will fire and create the Image Gallery.

Addendum

I don’t want to say that there aren’t other ways to do exactly what I did in this post. I just share what was, in my case, the solution that I implemented into my project and it worked. I will go deeper into JQuery Tools in future posts. Nevertheless, hope you find this post useful.



Tweet this!Tweet this!
Go to Top