Protocolos de comunicación AJAX

Un protocolo es una serie de reglas a seguir para poder establecer una comunicación entre 2 o mas programas, computadoras, entre otras.

Si haz desarrollado en Java usando threads y sockets, probablemente sabes a que me refiero, es importante establecer reglas y eviarlas "over the wire" para que se pueda establecer una conversación coherente.

Esto tiene mucho que ver con respuestas de XMLHttpRequest. En la arquitectura web tenemos 2 lugares de "trabajo", el server y el cliente. Estos 2 workspaces trabajan en un universo completamente diferente, esto quiere decir que variables del server no pueden ser vistas por el cliente, al menos de manera directa y por lo tanto una sentencia o accion de server no puede provocar un refresh del cliente (vdd nena? jaja) o viceversa. Cada dia salen mas y mas nuevas tecnologias que buscan acortar la distancia entre ambos "universos", sin embargo esto es solo una ilusion, al menos por ahora, pues solo son procedimientos que te hacen pensar que el lenguaje cliente y lenguaje server pudieran ser uno mismo cuando en realidad existen todo tipo de metodos o tweaks por atras. Para que este fuera posible, la arquitectura cliente-servidor deberia de rehacerse.

Muy bien, una vez aclarado esto es tiempo de comenzar.


Accion de server a Cliente

Muy bien, supongamos que tenemos una aplicación de chat en la web que se actualiza por medio de llamadas asincronas conectandose con el server cada 5 segundos, que sucede si en una de esas llamadas se nos niega la conección (Ya sea porque lo tumbaron, ya no esta loggeado u otras), como le hacemos para redirigirlo a la pagina de login??

Lo que tenemos que hacer es desarrollar un mini protocolo de comunicación entre el cliente y el server, que ambos lo entiendan (o al menos que nosotros lo entendamos).

por ejemplo:

Server (PHP)
 echo "{success:false, errorType:1, data:{...}}"

Cliente (Javascript)
 //Obtenemos la respuesta por medio de un XMLHttpRequest
 var response = eval(ajaxResponse);
 //Apartir de aqui, podemos hacer lo que queramos con el JSON
 if(response.errorType == 1){
   window.location = "../index.php"
 }

*El ejemplo es solo para motivos didacticos

Este tip es de lo mas sencillo, lo dificil para algunos es la arquitectura web, que se puede hacer y que no =P

Una vez que le agarramos la onda, todo tipo de loqueras se nos empiezan a ocurrir jaja.


Introduction to ExtJS

Hi! in my previous posts I talked about some basic tips and tricks any web and javascript developer should know and posted a very handy video that explains the rest of them. That should be more than enough to start learning the amazing world of ExtJS.

I'd like to add that I "discovered" ExtJS existence when I downloaded an open source project management application called opengoo which all of its main UI components were made by ExtJS.

What's ExtJS?


It's an amazing javascript framework!!...Amazing you say? indeed! It is a complete toolkit that enable us to make professional ajaxed web applications in minutes, without caring about css styling or performance, ExtJS does it for you.

In a Nutshell

The framework can be devided in two:

ExtJS Core : This is the utility library, whats that? well, have you heard of JQuery, prototype, yui? it's the same thing, it contains DOM Selectors, Animations, Event Handling and many more, but if you are more familiar with those above, ExtJS has something called "Adapters", this adapters will let you use Jquery or prototype as your core library insted of Ext's it will work the same.

ExtJS : This is an efficient, powerful and very well engineered widget library which has out of the box Grid Panels, Trees, Modal windows, menus, form controls and many more. All of this components were crafted using the best javascript patterns and practices that even enable you to extend all of the components functionality and even mix components to adapt to your application needs without making changes to the framework source.


ExtJS is going UP!

This framework has been rated by Gartner as "promising" for the near future along with adobe flex and others.

Since it is made of pure javascript code, html and css, its is possible to use this framework with adobe air and create desktop applications.

Avery day more developers are starting to use ExtJS, however the current user base have already created a bunch of custom opensource controls for you to use, you'll be amazed by those eye candy controls ;)


In the next post i'll create a "Hello ExtJS" till we get to "Creating Big Applications Using ExtJS" =) it's going to be interesting, stay tunned !

Bye!

All you need to know About javascript


This is one of the best tutorials I've found about javascript out there, its a compilation of the best techniques important for our everyday work.

I should've put this video instead of my last 2 posts ¬¬ hahaha

It's one hour long, but it's worth it!!!



How to structure your javascript. Part 2


Hi and welcome to the second edition of this javascript tutorial =)

In this tutorial I'm going to show Object Oriented capabilities (emulation) in javascript.
As you may know, javascript is an interpreted language and was not conceived to be object oriented for many reasons, actually nobody though it would be used as it is right now.

You can probably be wondering, why would I need this in js? well, I you like to become a javascript ninja, this is were you need to start.

In all of the next examples we're going to be using JSON (javascript object notation). If you have no clue what this is, take a look at this tutorial.

Let's begin =)

One of the neat features of the OO paradigm is to create "objects" which have methods and properties that "encapsulate" this characteristics within the object. In our first example we will create a car.


//car object first approach
var car = {
speed : 0
,accelerate : function(){
this.speed++;
}
,tachometer : function(){
alert(this.speed);
}
}

//Accelerate the car
for(var i = 0; i<=100; i++){
car.accelerate();
}

//How fast am I going?
car.tachometer();


In this example we created a car object which has properties (speed) and methods (accelerate, tachometer), using this approach we can only have one car, the one we just created and that's it, it is like a super variable (Singleton) with methods and properties and that's not too object oriented :S.
I use this approach as my application entry point were I initialize all of my components.


The second approach is as follows:

//car object second approach
var car = function(){
//Private Variables
var speed = 0;

return{
//Prublic variables
doors : 4
//Public functions with access to private variables
,accelerate : function(){
speed++;
}
,tachometer : function(){
alert(speed);
}
}
};

//create car instances
var bmw = new car();
var audi = new car();

//Accelerate the car
for(var i = 0; i<=100; i++){
bmw.accelerate();
}
//Notice that we haven't move our audi from the garage =P
bmw.tachometer(); // alerts 99
audi.tachometer(); // alerts 0


This example has more OO properties that the first one, here we have public and private variables and also methods plus with this approach we can create instances of the object and use it several times.

Important Note: Notice how some variables are declared using var and others not, when we use "var" inside a function the variable is "trapped" inside the scope of that function and any other that might be inside of it. I you declare variables without the "var" you're creating global variables attached to the "window" namespace.

I know i raised the bar a little bit in this post, so if I confuse any of you, let me know and I will modify the post.

Thanx for reading =)

How to structure your javascript. Part 1

Hi everyone, today i'll talk about javascript coding practices and how to structure your code to avoid variable collisions when making big js applications.

Every time a page is loaded, the client (browser) creates a variable/namespace called "window" which is like a little native framework provided on any page by the browser.
This namespace contains basic information about the client like view port width and height, the document variable, and many others. The naming of each variable can change from browser to browser and that's the primarily reason why javascript frameworks are created.

When we declare a js variable it is "stored" within the window namespace:

//run this code in Firebug console
foo = 1;
alert(window.foo);
alert(foo);

//Alerts 1 two times


As we can see, everything we declare this way is going to be saved withing the window namespace. Right now everything works perfect because we are using only one foo var, but what happen if we start creating a javascript widget which has a lot of functions and variables, we will "pollute" this namespace and ran out of names sooner or later.

If we want to keep our global namespace (window) clean, we can use an "anonymous" function to create a "closure" and encapsulate our variables inside. If you dont know what a javascript closure is, what are you waiting? take a look at this link.

Example:


//delete the foo variable from last example
delete foo;

(function(){
var foo = 1;

})();

//undefined uh?
alert(foo);



After running this snippet, we can take a look to the window variable in firebug and see that there's no "foo" variable listed inside, which means we can only use our foo variable inside that closure. Anonymous functions are very useful, it is also important to remember that a function in javascript is also a variable type along with strings, ints, arrays and objects:


var foo = function(){
alert("Function as a variable =)");
}

alert(typeof(foo));

//use it like this
foo();


This examples are very basic but i've found that no so many web developers know about 'em.

In part 2 we will continue with JSON classes and how they help us to emulate Object Oriented capabilities in javascript =) its going to be interesting and hopefully by the end of this series we will be able to start writing our own javascript framework =)

Thanx for reading!



First POOST!

Hi all! as everyone can seee, this is my first post!!! I've finally got the syntax highlight working now!!! I spent a lot of time looking for a good option and found this one. Its a widget for blogger!

I've been wanting to create a blog for sooo long and i though that free blogs were restrictive and that wont let me post my code samples screenshots and stuff and i was sooo wrong hehe.

Here i will be posting ExtJS Tutorials, Coding practices, design patterns and everything i learn on the road for me to use 'em everyday and for youu, so stay tuned =)


alert('HellYeahh!');