Category Archives: javascript

each() function in mootools don’t process associative arrays

Hi,

maybe this could sound obvious but is something that i didn’t know till a few days ago when i was making some changes on a js code i made. like the title says, the each() function used in mootools to apply a code to each element in the array, do not work with associative arrays.

so basically if you have this code:

var myArray=new Array();

myArray["key1"]="value1";

myArray["key2"]="value2";

myArray.each(function (item, index){

//do stuff

});

will not work, simply will not execute the loop on each array element. to fix this, you need to use the for loop like this:

var myArray=new Array();

myArray["key1"]="value1";

myArray["key2"]="value2";

for(key in myArray){

//do stuff

}

dunno if this is a mootools bug or was designed to work like this, but i hope this help you and save you time in debugging when you are using associative arrays.

update: from the comments below, let’s clarify some things:

*there is no associative arrays in javascript, they are objects, and i was wrong, indeed you can process it using the solution that Dimitar Christoff posted

var myArray= {};
myArray["key1"]="value1";
myArray["key2"]="value2";

Object.each(myArray, function (item, key){
console.log(item, key);
});

*when you process the object like this, you need to check that you are not processing the js methods that mootools define, personally i stop processing the object after i found the “$family” key, in the comments recommend to use the hasOwnProperty() function but i don’t see why is better or different than mine, if you know it, post it :)

thanks for the comments, i recognize when i’m wrong, for your collaboration, i’m a bit a better dev :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Stronger Passwords: NakedPassword

Hi,

i just saw this on my twitter TL and i think it worth a mini-post. All those who develop some application that require user authentication, deal with the password problem. is not only a problem to store passwords (BTW, i wrote another post about it recently) but also the problem is the user, trying to encourage him to use stronger ones, using uppercase, lowercase letters, number and symbols is not easy. usually most of the app’s have a bar that measure the strength of the password. is nice and useful, but most of the users just don’t pay attention to it. in this cases is where naked password take action and i will not say anything else, just go to the site and try it, is a twist in usability to say it in some way :P

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Multilanguage AJAX with the serialize function

Hi,

weeks ago i posted this function that basically let you serialize object and arrays in javascript and is compatible with the unserialize funcion in php. recently i discovered a problem in this function related with the management of the weird, other language characters. the problem is that when you save a word with, let say, russian characters, the count of the chars is different as how php do it, so when you try to unserialize the string you get a offset errors. to solve this, you need to convert the string into unicode, serialize it and then send it to the php.

the function to convert any string into unicode with javascript is the following:

function convertToEntities(tstr) {

  var bstr = '';

  for(i=0; i127)

    {

      bstr += '&#' + tstr.charCodeAt(i) + ';';

    }

    else

    {

      bstr += tstr.charAt(i);

    }

  }

  return bstr;

}

and in the php, you process the string like this:

$unserliazed= html_entityt_decode(unserialize($string),ENT_NOQUOTES, "UTF-8");

is very important that you set the UTF-8 charset to the decode function, so you get the original string.

also, remember that the database need to be support unicode-utf8, here you will find a quick guide for it

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Set wmode to flash and youtube iframe code with mootools

Hi,

recently, i have a problem with the flash content in a page that is customized by the user. the problem was that i popup a div with a higher z-index to show some info, this popup was not showing it in front of flash or youtube embed videos.  and to make it more difficult, this content was load using ajax and even that i could filter the information or the html code, i prefered to make it using javascript.

here i will share with you the function that process all the objects, embed and youtube iframe tags and set the wmode that you want to them.

function setWmode(mode,reinsert,youtube){
if(youtube==true){
var allIframes=$(document.body).getElements('iframe');
allIframes.each( function (item, index){
if(item.get('src').test('http:\/\/www.youtube.com\/embed\/')){
item.set('wmode',mode);
item.set('src',item.get('src')+"?wmode="+mode);
if(reinsert==true){
var newElem= item.clone(true,true);
var parentElem= item.getParent();
item.destroy();
parentElem.grab(newElem);
}
}
});
}
var allObjects=$(document.body).getElements('object');
allObjects.each(function (item, index){
var allParams=item.getChildren('param');
var WmodeExist=false;
allParams.each(function (item2, index2){
if(item2.get('name')=='wmode'){
item2.set('value',mode);
WmodeExist=true;
}
});
if(WmodeExist==false){
item.grab(new Element('param', {name: 'wmode',value: mode}));
}
if(reinsert==true){
var newElem= item.clone(true,true);
var parentElem= item.getParent();
item.destroy();
parentElem.grab(newElem);
}
});

var allEmbed=$(document.body).getElements('embed');
allEmbed.each(function (item, index){
item.set('wmode',mode);
if(reinsert==true){
var newElem= item.clone(true,true);
var parentElem= item.getParent();
item.destroy();
parentElem.grab(newElem);
}
});

}

this function requires of 3 paramenters:

mode: the value of wmode to set

reinsert: what this make is, clone the iframe/object/embed, erase the original and insert it again on the same location. this is made when you load the content before you set the wmode, so you can restart the load of the flash object and the wmode will have effect.

youtube: process or not youtube videos

i hope it help you in some way and save you maybe some time :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Improve Performance Tips

Hi,

today i wanted to give some common and not so common ideas of how to improve the performance of your web app. as you know, when you have a busy website, the performance (and along with the stability) is a key factor to have your project up and running, in this cases, you need to try to improve every aspect of your app, that is the idea, to help you to identify what can be or not be done in your case.

Database Optimization

Build a efficient database schema is not something easy, it cost time, study and testing to do it. at the time to build a efficient DB schema you need to take in consideration the following:

*Use the minimum columns as possible, and choose wisely the type of data that the database will store (if you will store number of 3 digit max, set a int(3) and not a varchar, text or a int(20))

*use the relational model, for dynamic or multiple values, use a index pattern where you have the definition of the data in 1 table and the data itself inserted by the user in other. do not create tons of columns as value_1, value_2 etc..

*add indexes to your tables

*use the primary key and unique key for columns that should have unique values to avoid data corruption or misbehavior.

in cases of the query, try to group the query’s in the less quantity of calls, use JOIN’s,  select only the columns that you will really going to use, don’t make generals select’s. in case you need to return the number of something, use functions as SUM() and not mysql_num_rows().

Clean and re-usable code

you need to be careful at coding too, even that php bring a big liberty whiteout having to worry about types and variable types, you need to be responsible for what you write. the php code get messy when you do messy stuff. organize variables, functions and classes as much as you can. i’ll recommend to use a MVC model if is possible (even that before i rejected it) and a framework will also make you life easier when you learn how to use it.

there is always a good practice separate the logic from the view (i mean the main php code from the design), for this you can grab any framework, most of them already support this or get a template engine. i have always used smarty, and is very flexible and you can extend it with custom functions and modifiers, also it support time cache and others types too. even that i’m happy with it, and i’ll recommend to you, i have realized with the time that is a waste if time. it will never be faster than the normal php code, so if you want to go really well, i’ll recommend you to get a or build a class that will just load the php script as templates and that’s it. you will save time from learning a template script and save process in the meantime

cache everything

this is one of the most important thing of all. the cache is the base of any optimization. let say true, most of the pages of any app doesn’t change and if they change dynamically, is usually for a user action. if this happen you can use a selective caching, where you cache at the event if a action. make this type of cache is not a easy task, takes time and testing, but really it make great results on the practice and worth the time invested on it. the cache of css and js files is also a good technique, as well the compress of them.

use the power of javascript

i learning caching a lot of stuff to use the power of javascript. i have cached pages that needed to be refreshed each 20 seconds. surely you are asking how i made it, so basically i just cached them once and filtered the results with javascript after the ajax load of the filter using JSON and the html code from other call. if you are wondering if this is really a performance advantage, well yes, you will see a 50% of difference from a normal php processing. anyway, be careful with this type of technique, remember that javascript run on the client side, so the information passed there can be manipulated in evil ways. is a powerful tool that need to be used very careful. also, i will recommend you to use a javascript framework, they are cross browser compatible for almost all their functions, with a big community and plugins available, and heavily optimized.

i hope this help you in some way at the moment to optimize your web app’s :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Crop images with mootools

Hi,

i’m still with the images stuff :)

now i needed to integrate a crop image script using js. so i started to look for a premade solution. you can find several of them here, here and here. i was looking for a mootools based solution and i found 4. for my surprise,one didn’t exist anymore,  one of them didn’t worked with mootools 1.2, the others was too complicated and not flexible and none offer what i really needed, that was able to offer “mirrors” as preview of the crop in 2 different sizes. in my adventure, i tried to fix the first one (MooCrop) porting it to 1.2 but i leave it why it would take me too much work, then i tried to modify cwCrop but the code structure seems to be less flexible, and finally i decided to go with uvumiCrop, as it already have a mirror function and just need to be converted into a multi-div function.

so for those who want the mirror feature in the uvumiCrop script, here are the functions and code you need to replace:

Add this to the class var declaration

previewImageArray:new Array(),

On some place around line 102, paste this

this.previewImageArray = new Array();

replace with this from lines 285 to 354

if(this.options.preview){
 if(isArray(this.options.preview)){
 var previewImgObjArray=new Array();
 this.options.preview.each(function (item,index){
 var initWidth= $(item).getStyle('width');
 var initHeight= $(item).getStyle('height');
 //we put the preview in a wrapper div with a fixed height, because preview height and width may change.
 var previewWrapperObj = new Element('div',{
 styles:{
 height:initHeight
 }
 }).wraps($(item));

 //Setting the preview container
 $(item).setStyles({
 display:'block',
 position:'relative',
 width:initWidth,
 height:initHeight,
 overflow:'hidden',
 margin:'auto',
 fontSize:0,
 lineHeight:0,
 opacity:1,
 visibility: 'visible'
 });

 //cloning the original image for the preview
 var previewImageObJ = this.target.clone();
 previewImageObJ.set('id','imgObj_'+index);
 previewImageObJ.removeProperties('width','height').setStyle('position','absolute').inject($(item));
 previewImgObjArray.push(new Array('imgObj_'+index,item,initWidth,initHeight));
 }.bind(this));
 this.previewImageArray=previewImgObjArray;
 }else{
 if($(this.options.preview)){
 this.preview = $(this.options.preview);
 //we put the preview in a wrapper div with a fixed height, because preview height and width may change.
 this.previewWrapper = new Element('div',{
 styles:{
 height:this.previewSize.y+2*this.preview.getStyle('border-width').toInt()+this.preview.getStyle('margin-top').toInt()+this.preview.getStyle('margin-bottom').toInt()
 }
 }).wraps(this.preview);
 }else{
 var previewWrapper = new Element('div',{
 'class':'preview'
 }).inject(this.toolBox,'top');
 this.preview = new Element('div').inject(previewWrapper)
 }

 //Setting the preview container
 this.preview.setStyles({
 display:'block',
 position:'relative',
 width:this.previewSize.x,
 height:this.previewSize.y,
 overflow:'hidden',
 margin:'auto',
 fontSize:0,
 lineHeight:0,
 opacity:0
 });

 //cloning the original image for the preview
 this.previewImage = this.target.clone();
 this.previewImage.removeProperties('width','height').setStyle('position','absolute').inject(this.preview);
//            this.addEvent('onPreview',this.updatePreview.bind(this));
 }
 this.addEvent('onPreview',this.updatePreview.bind(this));
 }

replace updatePreview function with this code below:

//Function to update the preview
 updatePreview: function(top,left,width,height){
 if(this.previewImageArray.length>0){
 this.previewImageArray.each(function (item,index){
 if(height*item[2].toInt()/width<item[3]){
 $(item[1]).setStyles({
 width:item[2],
 height:(item[3].toInt()*height/width).toInt()
 });
 $(item[0]).setStyles({
 width:(this.target_coord.width*item[2].toInt()*this.scaleRatio/width).toInt(),
 height:'auto',
 top:-(top*item[2].toInt()/width).toInt(),
 left:-(left*item[2].toInt()/width).toInt()
 });
 }else{
 $(item[1]).setStyles({
 height:item[3],
 width:item[3]
 });
 $(item[0]).setStyles({
 height:(this.target_coord.height*item[3].toInt()*this.scaleRatio/height).toInt(),
 width:'auto',
 top:-(top*item[3].toInt()/height).toInt(),
 left:-(left*item[3].toInt()/height).toInt()
 });
 }
 }.bind(this));
 }else{
 if(height*this.previewSize.x/width<this.previewSize.y){
 this.preview.setStyles({
 width:this.previewSize.x,
 height:(this.previewSize.x*height/width).toInt()
 });
 this.previewImage.setStyles({
 width:(this.target_coord.width*this.previewSize.x*this.scaleRatio/width).toInt(),
 height:'auto',
 top:-(top*this.previewSize.x/width).toInt(),
 left:-(left*this.previewSize.x/width).toInt()
 });
 }else{
 this.preview.setStyles({
 height:this.previewSize.y,
 width:(this.previewSize.y*width/height).toInt()
 });
 this.previewImage.setStyles({
 height:(this.target_coord.height*this.previewSize.y*this.scaleRatio/height).toInt(),
 width:'auto',
 top:-(top*this.previewSize.y/height).toInt(),
 left:-(left*this.previewSize.y/height).toInt()
 });
 }
 }
 },

and the isArray() function used at the beginning of the code:

function isArray(obj) {
 return obj.constructor == Array;
}

so, now in the initialization of the uvumiCrop object, you set the preview property as a array ( new Array(‘id1′,’id2′) ) with the id’s of the divs that will be used as mirrors. is important that you set the width and height of each div before you create the uvumiCrop object. this code will maintain the original behavior of the original script, you can still have the floating mirror and the unique mirror.

is also important to mention that i changed the code so the container don’t get the width and height deformed and work as a container hiding the rest of the image. is done like this so the user can know really how it will look after the crop process.

i have sent this post to the developer, so maybe he include it on the next release :D

i hope you find this useful and save you some time :D

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post

Autocomplete plugin for mootools

Hi,

recently building a app i was need to suggest data to the user when trying to fill a input. so i look for a js script for this. i usually use mootools for my development in js, so looking for a plugin i found this: Meio.Autocomplete plugin for mootools

is a really nice plugin, between their features, support the inbuilt ajax calls using the Request.JSON method from the mootools framework. also support to set up filter for the returned data, the set of field parameter to look for the input by the user, the minimum of characters that the user need to enter to start looking for it, delay between the ajax call and the search in the data and many other properties. you can also customize the look and feel of how the options are displayed.

from their web page you can download the source code and the compressed version for production environments. also there you can see plenty of documentation explaining each property of the plugin and several examples to see and try online.

i hope it help you in some way :)

Regards,

Shadow.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Related Post