Asv3's Blog

October 12, 2009

Asynchronous Javascript + XML

Filed under: javascript — Tags: , , , , , , — asv3 @ 9:18 pm

Ajax or Asynchronous Javascript + XML started with Jesse James Garrett penning an online article on usage of XHR aka XMLHttpRequest object in 2005. Idea behind Ajax was to give user data/page updates without refreshing the page. By Doing so Ajax made static boring HTML pages to be highly interactive and exciting. Later on developers and designers around the world came up with enhanced use cases and patterns for using Ajax. Prior to XHR object ajax kind of functionality was being achieved using lot many hacks, mostly involving hidden frames or iframes, Java Applets and Flash movie. XHR introduced streamlined interface for making server requests and evaluating responses. Despite having XML in it’s name Ajax is format-agnostic; the technique basically is about retrieving data from server without refreshing page.

Microsoft first introducing this functionality in IE5, later an other browsers started implementing and Ajax was the buzz word in late 2005 and early 2006. IE browsers before IE 7 needed using one of MSXML2.XMLHttp ,  MSXML2.XMLHttp.3.0 , and MXSML2.XMLHttp.6.0 to be used in order to create XHR object, code for creating XHR object in browser < IE 7 looks like this.

function createXHR(){

    if(typeof arguments.callee.activeString != "string"){

        var versions = ["MXSML2.XMLHttp.6.0", "MXSML2.XMLHttp.3.0","MXSML2.XMLHttp"];

        for(var i=0, len = versions.length; i<len;i++ ){

            try{

                var xhr = new ActiveXObject(versions[i]);

                arguments.callee.activeXString = versions[i];

                return xhr;

            }catch (ex){

                //skip

            }

        }

    }

    return new ActiveXObject (arguments.callee.activeXString);

}

IE 7, Firefox, Opera, Chrome and Safari all support a native XHR object that can be created using,

var xhr = new XMLHttpRequest();

if you need to support you first check for XMLHttpRequest support, if supported return that object else continue with above mentioned function.

XHR object usage looks like this.

var xhr = new XMLHttpRequest();

xhr.open("get","yourdata.php", false); // arguments in order HTTP method, url, asynchronous true/false;

xhr.send(null)

if you pass third argument asynchronous as false, you are making and synchronous server call, javascript execution wait till server respond with result. when the response is received XHR object will have result assigned to it’s properties as follows:

responseText – Text in body of the response
responseXML -  Contains XML DOM document with response data if the response has content type set to "text/xml" or "application/xml"
status – HTTP status of the request
statusText – Description of HTTP status.

Where are setting third argument asynchronous as true will allow you to make asynchronous call, which doesn’t halt javascript execution till the request is completed. but you need to check readyStage of XHR object to track status of the request, readyState can have following possible values

0 – Un-initialized
1 – Initialized but not called send()
2 – Sent, send() called
3 – Receiving, partial response is received
4 – Complete, received complete response

whenever ready state changes from one to another readystatechange event gets fired, adding a listener/function to this event will let you track status of the XHR request.

// ready state tracked code looks like this

var xhr = createXHR();       

xhr.onreadystatechange = function(){

    if (xhr.readyState == 4){

        if ((xhr.status  > = 200  &  &  xhr.status  <  300) || xhr.status == 304){

            alert(xhr.responseText);

        } else {

            alert(“Request was unsuccessful:+ xhr.status);

        }

    }

};

xhr.open(“get”, “example.txt”, true);

xhr.send(null);  ((

// you can cancel an asynchronous request by using xhr.abort();

September 26, 2009

Prototype Chains

Filed under: front-end, javascript — Tags: , , , , , , — asv3 @ 10:27 pm

Whenever you try to access some property of a JavaScript object, it will look for that property in 2 places. First one is Object itself and second one is Object’s prototype. If prototype of that Object is another Object then search moves on that Object and that Object’s prototype. Search like this carried till it reach that accessed property to return value or native JavaScript Object, of which prototype is nothing but null and returns null. this feature of JavaScript is called as Prototype Chains

Objects in javaScript

Filed under: front-end, javascript — Tags: , , , , — asv3 @ 10:26 pm

An Object in JavaScript is a collection of un-ordered properties each of which contains a primitive value, object or function.

Simplest way of creating object is creating new instance of Object and add properties into it.

Example:

var pet = new Object()

pet.name = "Dev";

pet.age = 2;

pet.type = "dog"

pet.whatPet = function(){

    alert(this.type);

}

 

But when you have to create many instances of a given object you need to use lot many redundant code. Hence to avoid programmers started introducing Factory pattern to create new objects.

Factory pattern is popular design-pattern which is used to abstract away process of creating specific objects.

Pet class creation code with Factory pattern looks like this.

function createPet(name, age,type){

    var o = new Object();

    o.name = name;

    o.age = age;

    o.type = type;

    o.whatPet=function(){

        alert(this.type);

    }

    return o;

}

 

var dog1= createPet("Dev",2,"dog");

var cat1= createPet("Cuty",1,"cat");

 

Using this method will soft problem of redundancy but by this way we cannot identify type of an object. This problem was again resolved using Constructor pattern.

function Pet(name, age,type){

    this.name = name;

    this.age = age;

    this.type = type;

    this.whatPet=function(){

        alert(this.type);

    }

}

 

var dog1= new Pet ("Dev",2,"dog");

 

A constructor function defers from normal function just in the way it is called, otherwise syntax remains same for both the functions. Constructor function can be called as follows:

var dog1 = new Pet ("Dev",2,"dog");

dog1.whatPet();

 

//or calling it like functions

 

Pet("Dev",2,"dog");

window.whatPet();

 

// all objects reside in global context can be referred by window.

 

var o = new Object();

Pet.call(o,"Dev",2,"dog");

o.whatPet();

 

Only problem with constructor is whatever methods you define they won’t share same instance of functions. Each instance of given object with create its own function instance for each method.  There is no point in having multiple instances of the same Function.

 

to be continued…

September 20, 2009

JavaScript Syntax

Filed under: Uncategorized — Tags: , , — asv3 @ 10:29 pm

Identifiers in JavaScript should start from a letter/underscore or a dollar sign, all other characters might be letters, underscores, dollar signs, or numbers.

You cannot use a key word as an identifier.

In JavaScript every thing is case sensitive. something differs from someThing.

you can single line and multi line comments similar to C language.

//single line comment

/*
* This is a multi-line
* Comment
*/

/*

* This is a multi-line

* Comment

*/

A semicolon at end of each statement is preferred but not mandatory.

Things to Remember about JavaScript

Filed under: javascript — Tags: , , , , , — asv3 @ 12:37 pm

About <script> element

  • language attribute is deprecated and should not be used.
  • defer attribute not supported by all browsers
  • using “<” in script within a XHTML throws syntax error, you should use CDATA directive
  • type attribute should set to “text/javascript” to maximize browser comapatability
  • using “</script>” anywhere in the script brakes code execution, if you happen to use you can use “</scri”+”pt>”
  • external JavaScript inclusion looks like “< script type=”text/javascript” src=”example1.js” > < /script >”
  • use
    < script > < !–
    function sayHi(){
    alert(“Hi!”);
    }
    //– > < /script >

    < script > < !– and //– > < /script > to make sure, non-JavaScript browsers don’t display JavaScript as body content.

Inline V/s External scripts:

External scripts provide following better  maintainability and caching benefits

September 19, 2009

Interface with JavaScript

Filed under: javascript — Tags: , , , , — asv3 @ 6:19 pm
Interface: An interface is an blue print of a class, it specify what methods an Object should have, that way it add some kind of predictability on what you can expect from that Class. For example, a Class that implement “Comparable” interface can be assumed to be comparable with other object that implement “Comparable” interface. It allows you to group objects on the features they provide. It make sure all Classes of required feature follows same methods, hence communication between them easier. In a way it also increases code re-usage.
JavaScript doesn’t have native support for interfaces along with normal object oriented features of other languages like C++ and Java. There is no interface keyword in JavaScript, apart from this emulating interfaces feature will add some performance over head and will reduce the flexibility of JavaScript to some extent. Transition for other language codes to JavaScript may be a tedious task, if you developing completely new Class, you can make sure all implementations are at their best ability. Biggest of the problems in using interfaces with JavaScript is there is no way you can force other programmers to use the interfaces you created.

Interface: An interface is an blue print of a class, it specify what methods an Object should have, that way it add some kind of predictability on what you can expect from that Class. For example, a Class that implement “Comparable” interface can be assumed to be comparable with other object that implement “Comparable” interface. It allows you to group objects on the features they provide. It make sure all Classes of required feature follows same methods, hence communication between them easier. In a way it also increases code re-usage.

JavaScript doesn’t have native support for interfaces along with normal object oriented features of other languages like C++ and Java. There is no interface keyword in JavaScript, apart from this emulating interfaces feature will add some performance over head and will reduce the flexibility of JavaScript to some extent. Transition for other language codes to JavaScript may be a tedious task, if you developing completely new Class, you can make sure all implementations are at their best ability. Biggest of the problems in using interfaces with JavaScript is there is no way you can force other programmers to use the interfaces you created.

Examples to follow

Anonymous Functions, Closure

Filed under: javascript — Tags: , , , , , , — asv3 @ 7:55 am

JavaScript is loosely typed language. You don’t define data type while you declare any variable. But it’s not like it won’t belong to any data type, depending on the value you store, variable automatically changes it’s data type.

Type Casting is possible with JavaScript. But it happens so easily that you don’t have to worry on the type casting.Primitive data types in JavaScript are

  1. Number
  2. String
  3. Boolean
  4. null
  5. undefined

these are the primitive data types, there are other non-primitive data types like Array, Function etc. Primitive data types are passed by value, where as non-primitive data types passed by reference.

Anonymous Functions: A function that is defined without a name is called Anonymous Function. In JavaScript Functions are first-class objects, you can do almost any thing with functions,

  • you can assign them to variables
  • pass as arguments to functions
  • return as result from a function
  • can be constructed run-time

These are the features on JavaScript which makes this language more exiting.

here is an example of anonymous function:

/* Anonymouse Function */

(function(){

    var a=10;

    var b=20;

    alert(a+b);

})();

 

/*Anonymous Function with arguments */

(function(a,b){

    alert(a+b)

})(10,20);

 

 

/* Anonymous function that returns a value */

var sum = (function(a,b){

    return a+b;

})(10,20);

 

//sum eaual tp 30.

Most interesting use of anonymous function is closure. Closure is a protected variable space, created by using nested functions. Here is an example with closure.

var sum;

(function(){

    a=10;

    b=20;

    sum = function (){

        return a+b;

    };

})();

sum has access to a and b, even though it’s executed outside of the anonymous function.

September 18, 2009

Flexibility & JavaScript

Filed under: front-end, javascript — Tags: , , , , , — asv3 @ 10:03 pm

JavaScript is the most flexible and widely used language in current era of Internet, nobody expected JavaScript to grow this fast and wide, hence I say JavaScript is kind of under-developed but over used technology. But that doesn’t take the beauty of flexibility away from JavaScript even though security remains major concern in its implementation. Every day it keeps me interesting with it’s abilities, every time I think why did I miss that part it. In all it’s the most flexible language for OO coding, here is the small example which shows how you can easily organize and maintain JavaScript code.

 

Say I have to define 2 functions walk and run. you can define them as follows.

function walk(){

    // do walking

}

 

function run(){

    // do running

}

 

If you are defining this function as part of a Man class, code looks like this

var Man=function(){

    //….

};

 

Man.prototype=function(){

    // do walking

};

 

Man.prototype.run=function(){

    // do running

};

 

/* Usage */

 

var ravi=new Man();

ravi.walk();

ravi.run();

If you want class encapsulated in one declaration you can do

 

var Man=function(){

    //….

};

Man.prototype={

    walk:function(){

        // do walking

    },

    run:function(){

        //do running

    }

}

What’s next you can add a method to Function object that can be used to declare methods.

Function.prototype.method = function(name, fn) {

    this.prototype[name] = fn;

};

var Man= function() {

    //do something

};

Man.method(‘walk’, function() {

    //do walking

});

 

Man.method(‘run’, function() {

    //do running

});

 

As we saw earlier, flexibility of JavaScript is enviable, here every thing is an object (except primitive data types) and you can add attributes and methods to these Objects at any point of time, execution. You can even add methods and attributes to Functions as well. Here is an example:

function displayError (message){

    displayError.numTimesExecuted++;

    alert(message);

}

displayError.numTimesExecuted = 0;

here is another example with prototype:

function Man(weight, height){

    this.height = height;

    this.weight = weight;

}

 

Man.prototype={

    getHeight:function(){

        return this.height;

    },

    getWeight:function(){

        return this.weight;

    }

}

 

/* Initiating the class */

 

var ravi = new Man (80,164);

var suresh = new Man (75,169);

 

/* add new method to Class */`

Man.prototype.getGreeting=function(){

    return "Hi your height and weight is " + this.getHeight() +"  and " + this.getWeight() + " respectively";

}

ravi.getGreeting();

//output "Hi your height and weight is 164 and 80 respectively"

Object Oriented Javascript

Filed under: general — Tags: , , , , , — asv3 @ 9:35 pm

I keep hearing now a days, OO Javascript is the buzz word, may be the time has come to think that who-ever can implement OO concepts in Javascript rule the front-end development. Is that completely true? I don’t think so, whatever technique people are using to do OO Javascript are outdated techniques in ActionScript. We with ActionScript started using prototype long before even Flash MX 2004 and ActionScript 2 arrived. That was the only way to write manageable code in ActionScript by then.  I remember doing some games using such methods, we used to use #initclip #endinitclip to define ActionScript code that need to be executed before MovieClip is initialized. All done, but it’s OO Javascript creating a wave now in Front-End development. But I can say it’s time for us to do some thing interesting with JavaScript, when every body telling the OO JS is cool, that should have some thing super cool in it. Please join us in exploring super cool features on JavaScript in coming days.

Blog at WordPress.com.