Monday, January 4, 2010

What is DOJO and its introduction


Dojo is an Open Source DHTML toolkit written in JavaScript. It builds on several contributed code bases (nWidgets, Burstlib, f(m)), which is why we refer to it sometimes as a "unified" toolkit. Dojo aims to solve some long-standing historical problems with DHTML which prevented mass adoption of dynamic web application development.

Dojo allows you to easily build dynamic capabilities into web pages and any other environment that supports JavaScript sanely. You can use the components that Dojo provides to make your web sites more usable, responsive, and functional. With Dojo you can build degradable user interfaces more easily, prototype interactive widgets quickly, and animate transitions. You can use the lower-level APIs and compatibility layers from Dojo to write portable JavaScript and simplify complex scripts. Dojo's event system, I/O APIs, and generic language enhancement form the basis of a powerful programming environment. You can use the Dojo build tools to write command-line unit-tests for your JavaScript code. The Dojo build process helps you optimize your JavaScript for deployment by grouping sets of files together and reuse those groups through "profiles".

Dojo does all of these things by layering capabilities onto a very small core which provides the package system and little else. When you write scripts with Dojo, you can include as little or as much of the available APIs as you need to suit your needs. Dojo provides multiple points of entry, interpreter independence, forward looking APIs, and focuses on reducing barriers to adoption.


Friday, December 11, 2009

JavaScript Optimization Tips


Always use the "var" deceleration for local variables.
Why? It tells JavaScript that the variable is local, i.e. JavaScript won't look for the variable in the outside scope.

Always use local decelerations for lookups that you use multiple times.
Why? JavaScript code isn't optimized, so lookups wont be cached.


Wednesday, November 11, 2009

Overview of JSON with sample code



JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another.


The Object: An Introduction


Behold, an Object…
var myFirstObject = {};
It may not look like much, but those squiggly braces have the potential to record every bit of information humanity has ever gathered, and express the most complex programs computer scientists can dream up. In fact, Javascript itself is stored inside a set of squiggly braces just like that, as are all of its primitive data types -- strings, numbers, arrays, dates, regular expressions, they're all objects and they all started out just like myFirstObject.


Creating A New Object


The old way to create a new object was to use the new keyword.
var myJSON = new Object();
This method has been deprecated now in favor of simply defining an empty object with squigly braces…
var myJSON = {};


Objects as Data


At its most base level a Javascript Object is a very flexible and robust data format expressed as name/value pairs. That is, an object holds a name which is an object's property -- think of it as a plain old variable name that's attached to the object name. And the object holds the value of that name. Here's an example…
var myFirstJSON = { "firstName" : "John",
                   
"lastName"  : "Doe",
                   
"age"       : 23 };

document
.writeln(myFirstJSON.firstName);  // Outputs John
document
.writeln(myFirstJSON.lastName);   // Outputs Doe
document
.writeln(myFirstJSON.age);        // Outputs 23
This object has 3 properties or name/value pairs. The name is a string -- in our example, firstName, lastName, and age. The value can be any Javascript object (and remember everything in Javascript is an object so the value can be a string, number, array, function, even other Objects) -- In this example our values are John, Doe, and 23. John and Doe are strings but age is a number and as you can see this is not a problem.
This data format is called JSON for JavaScript Object Notation. What makes it particularly powerful is that since the value can be any data type, you can store other arrays and other objects, nesting them as deeply as you need. 


Accessing Data In JSON


The most common way to access JSON data is through dot notation. This is simply the object name followed by a period and then followed by the name/property you would like to access.


var myObject = { 'color' : 'blue' };



document
.writeln(myObject.color); // outputs blue.
If your object contains an object then just add another period and name…


var myObject = { 'color' : 'blue',

                 
'animal' : {'dog' : 'friendly' }

               
};



document
.writeln(myObject.animal.dog); // outputs friendly



Sunday, November 1, 2009

Introduction to JQuery




jQuery  : 

jQuery is a fast and concise JavaScript Library thatsimplifies HTML document traversing, event handling, animating, and Ajaxinteractions for rapid web development. jQuery is designed to changethe way that you write JavaScript. jQueryis great library for the JavaScript programmers, which simplifies thedevelopment of web 2.0 applications. You can use jQuery to develop cool web 2.0applications.
jQuery library simplifies theprocess of traversal of HTML DOM tree. You can use jQuery to handle events,perform animation, and add the ajax support into your web applications withease.



Uses of  jQuery :


You can use simple JavaScript toperform all the functions that jQuery provides. Then why jQuery? The jQuerylibrary is providing many easy to use functions and methods to make richapplications. These functions are very easy to learn and even a designer canlearn it fast. Due to these features jQuery is very popular and in high demandamong the developers. You can use jQuery in all the web based applications,
irrespective of the technology.

jQuery is java script and can beused with JSP, Servlets, ASP, CGI, PHP and almost all the web programminglanguages.


The jQuery code is very simple andeasy to learn.


The features of jQuery :
  • DOM element selections functions
  • DOM traversal and modification
  • Events
  • CSS manipulation
  • Effects and animations
  • Ajax
  • Extensibility
  • Utilities - such as browser version and the each function.
Time required to learn jQuery :


You can learn jQuery in a day andmaster it within 2-3 days. There are so many features available with jQuery andyou may spend months to explore these features.



Tuesday, October 27, 2009

Understanding AJAX


AJAX is a technique rather than a technology: It describes how JavaScript can be used to pull data from the server using the XML HTTP Request object and then insert this data into the website using DOM. This is done asynchronously - that is, in the background, without having to refresh the whole page. The technology which AJAX is based on has already been available for a while, the combination is what makes it new.You can try the examples online or download them and run them locally (except for the PHP script, that would require a webserver with PHP).Simple (html)example shows how to set the content of the


<script type="text/javascript">
function replace() {
 document.getElementById('foo').innerHTML = "Hello, <b>AJAX</b>world!";
}
</script>


<p><a href="javascript:replace()">ReplaceText</a></p>


<div id="foo">
  Hello, world!

The XML HTTP Request objectThe XML HTTP Request object is used to make HTTP requests. This is the core object that is reqd for doing an AJAX call.

Simple script which shows the required steps for doing an AJAX call.

<script type="text/javascript">
var http = false;


if(navigator.appName == "Microsoft Internet Explorer") {
  http = newActiveXObject("Microsoft.XMLHTTP");
} else {
  http = newXMLHttpRequest();
}


http.open("GET", "test.txt");
http.onreadystatechange=function() {
  if(http.readyState == 4) {
   alert(http.responseText);
  }
}
http.send(null);
</script>

Combining the Simple Html example with the XMLHttpRequest (above script) gives us AJAX

<script type="text/javascript">
var http = false;


if(navigator.appName == "Microsoft Internet Explorer") {
  http = newActiveXObject("Microsoft.XMLHTTP");
} else {
  http = newXMLHttpRequest();
}


function replace() {
  http.open("GET","test.txt", true);
 http.onreadystatechange=function() {
    if(http.readyState == 4){
     document.getElementById('foo').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>


<p><a href="javascript:replace()">ReplaceText</a></p>


<div id="foo">
  Hello, world!
</div>

While the previous example fully demonstrated AJAX, it was totally boring. Including the contents of a static file into the page could have been done much easier, you might say. However, AJAX becomes powerful when combined with a server-sided script. Consider the following PHP script, which validates a user name entered into a form. The name chosen has to be at least three letters long and must still be available:

<?php
function validate($name) {
  if($name == '') {
    return '';
  }
 
  if(strlen($name) < 3) {
    return "<span id=\"warn\">Username too short</span>\n";
  }
 
  switch($name) {
    case 'bob':
    case 'jim':
    case 'joe':
    case 'carol':
      return "<span id=\"warn\">Username already taken</span>\n";
  }
 
  return "<span id=\"notice\">Username ok!</span>\n";
}
 
echo validate(trim($_REQUEST['name']));
?>

Simple html page, which makes the call to the PHP code….

<script type="text/javascript">
var http = false;
 
if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}
 
function validate(user) {
  http.abort();
  http.open("GET", "validate.php?name=" + user, true);
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('foo').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>
 
<h1>Please choose your username:</h1>
 
<form>
  <input type="text" onkeyup="validate(this.value)" />
  <div id="foo"></div>
</form>

Now enter a name into the text field. Try bob, jim, joe orcarol. The <div> will update as you type, giving you information onwhether your username is valid. Also note the http.abort();, which will abort theprevious request, if a new one comes in. This is useful when the user typesvery quickly. The script could probably improved by waiting a couple of secondsafter the user has typed a name. While the server's response is nearlyinstantaneous, this also causes a lot of HTTP requests resulting in a lot ofserver load.
Browsers that do not support AJAX will not display this information, whichdoes not matter at all, because the validation can also be done when the usersubmits the form.
Congratulations! If you came this far, you now understand AJAX. By the way,replacing a <div> using HTML generated from a script is the most commonway to use AJAX.Other possibilities include serializing the data asJSON, which isbasically an object in JavaScript notation, which can then just be eval()'ed. The advantage here is that the data can befurther manipulated in JavaScript.

Imp: We can also use other Server side scripting language likeJava Servlets / .net.. instead of the PHP.