Category Archives: AJAX

What is AJAX?

Some more old notes on AJAX and related stuff

1. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. The term talks about how to asynchronously retrieve data from server using JavaScript and XML, but actually, AJAX goes much beyond that. It is more about providing a rich experience to users. A rich user experience can be simply stated as a ‘desktop application like feel’; now, desktop applications can have the luxury of heavy weight rich User Interfaces and with AJAX the same is possible for web applications, which so far could afford only a basic UI. With AJAX, the need for reloading the UI again and again with every request is gone; we will understand this more in rest of the document.

AJAX in itself is not a language or a framework. It is a technique. It basically uses XMLHTTPRequest Object to fetch the data from server without reloading the page. Additional AJAX supporters are CSS, DOM, DHTML and XSL.

Another keyword you will observe is Asynchronous. Asynchronous communication in general terms means that a browser does not wait for a reply from server once a request is sent. Hence, it does not stop user from interacting with the page while the information is being fetched from server. The data is retrieved as a back ground process and the web page does not get refreshed, the data is displayed dynamically at runtime giving the web application a feel of desktop application and hence improves user experience.

You might question if AJAX is more than just JavaScript and XML, why is it called AJAX? This is what Jesse James Garrett, the man who coined the term AJAX has to say about it “I needed something shorter than ‘Asynchronous JavaScript + CSS + DOM + XMLHttpRequest’ to use when discussing this approach with clients.” hence the term AJAX

2. Where do we use AJAX?

You are already familiar with AJAX if you are a frequent user of internet. Some of the example sites are Flickr, GMail, Hotmail, Google Suggest, or Google Maps. Following uses of AJAX should give you a pretty good picture of what it is capable of doing

2.1. Real time Form Validation: You have a form which asks for your email address. A simple JavaScript will help to check that it has a ‘@’ and a ‘.’ Properly, but what if we want to check that if this email address is already present in database or not. For this we need to hit the server and check the database. Conventionally the operation would refresh the page, but with AJAX the validation can be done at the backend and a message can be shown to the user that the email address is in use without refreshing the page.

2.2. Real time On-Demand Data fetching: You are looking for branches of a bank in a city, there are two columns in the form- City and Address. You provide city and it gives you the addresses. Now one way to achieve this is get all the data regarding all the addresses in all the cities beforehand in the JavaScript. So if bank has 20 branches each in 20 cities, we are fetching 400 records, though user only requests for one city. With AJAX we don’t need to pre-populate our dataset as we can do that once user enters the city name.

2.3. Auto-Completion of text: At some websites you will notice that while you are typing it shows a list of suggestion that is through magic of AJAX. Examples are Google suggest where you get a list of suggestions for the terms which you might want to search or on railway booking site when you are entering name of a place and it autosuggest the station names based on letters you have entered so far.

2.4. Server Push: You are on your email website. The page is open for last 10 mins and now you want to check if you have received any email during that period. Ideally you would refresh the page, but with AJAX it will keep updating the website as and when any emails are revied. A similar example would be a stocks website which keeps displaying latest stock price without any action.

2.5. Rich User Interfaces: As we do not need to upload the UI again and again, we can have the luxury of rich UI. If there are multiple pages in a web application, but the base UI is same for all, AJAX helps sending the UI only once. The next time server will only send the updated contents which would be rendered in the existing UI.

3. Main constituents of AJAX

While working on an AJAX application you will come across the following terms. Combination of one or more of these technologies can be used to create an AJAX application

3.1. DOM

DOM or Document Object Model is a W3C standard set of objects for representing HTML or XML. The DOM model is platform independent and is used by JavaScript to modify and render HTML pages on runtime.

3.2. XML

XML stands for EXtensible Markup Language. It is widely accepted format for transporting and storing of the data. One can create any tags in a way data is required to be saved. It is hierarchical representation of data, where at the top we have parent which will have child nodes and then sub-Childs and so on. We need to parse the XML in order to retrieve the desired data. The following example should help understanding the XML format

<Employees>
<Employee>
<Name>John</Name>
<EmployeeNum>1234</EmployeeNum>
<Designation>PA</Designation>
<Employee>
<Employee>
<Name>Eric</Name>
<EmployeeNum>1232</EmployeeNum>
<Designation>SE</Designation>
<Employee>
<Employee>
<Name>Tim</Name>
<EmployeeNum>1233</EmployeeNum>
<Designation>PM</Designation>
<Employee>
</Employees>

3.3. XMLHttpRequest (XHR)

For AJAX, XMLHttpRequest is the backbone object. It is the technical component that makes the asynchronous server communication possible. The XHR is DOM API which can be used by JavaScript to send and receive data from server from client side. Normally the data fetched is in form of XML, text or JSON.

Creating an Object of XHR is simple. For Browsers like Mozilla, Safari, Opera etc. Use

var request=new XMLHttpRequest();

For Internet Explorer, depending on the version of JavaScript, one of the two would work

Var request= new ActivexObject(‘Microsoft.XMLHTTP’);
Or xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

The following method would give an XHR object for almost all the browser

//For IE
var xmlHttpRequest= false;
try {
xmlHttpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlHttpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e2) {
xmlHttpRequest = false;
}
}
//For Others
if (!xmlHttpRequest) {
xmlHttpRequest = new XMLHttpRequest();
}

Once we get the XHR object, it provides us following Properties and Methods

Properties

Property Description
onreadystatechange This is an evenlistener property, which is called whenever readyState property changes
readyState This can have following five states
0 = not initialized (open () method not called yet)
1 = loading (send () method not called yet)
2 = loaded (send() method id called, and header and status information is available)
3 = interactive (the responseText property has some partial data)
4 = complete (communication finished)
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
Status Status code returned by server, such as 404 for “Not Found” or 200 for “OK”
statusText String message accompanying the status code

Methods

Method Description
abort() Cancel’s the current request
getAllResponseHeaders() Returns complete set of response headers (labels and values) as a string
getResponseHeader(“headerLabel”) Returns the string value of a single header label
open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]]) Prepares the XHR request by assigning
Method: Get or Post
URL: URL to be called
Asynchronous Flag: Whether the data needs to be sent asynchronously or not
Username: Optional
Password: Optional
send(content) Transmits the request, with the optional content which can be postable string or DOM object data
setRequestHeader(“label”, “value”) Assigns a label/value pair to the header to be sent with a request

3.4. JavaScript

JavaScript is a scripting language, which helps dynamically interacting with HTML pages. It is widely used to do perform runtime form validation checks on the client side.

For AJAX applications, role of JavaScript is very important as this is used to handle events on HTML pages and dynamically updates the contents, which is basis of any Rich Internet applications. Though JavaScript is not the only Scripting language which can be used, but it is the most common and widely used.

3.5. DHTML

DHTML or Dynamic HTML is a combination of multiple technologies like HTML, JavaScript, DOM, and CSS. The purpose of DHTML is to make web pages dynamic and interactive.

According to the World Wide Web Consortium (W3C):
“Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated.”

For example we can update the contents of an HTML page at the runtime like
document.getElementById(id).innerHTML= ‘change it’

3.6. XSL
XSL stands for eXtensible Stylesheet Language is a family of recommendations for defining XML document transformation and presentation. XSL is not directly playing any role with AJAX applications, but in case you try to use XML to create the HTML pages this will come handy.
The XSL family comprises three languages:
XSL Transformations (XSLT): an XML language for transforming XML documents
XSL Formatting Objects (XSL-FO): an XML language for specifying the visual formatting of an XML document
XML Path Language (XPath): a non-XML language used by XSLT, and also available for use in non-XSLT contexts, for addressing the parts of an XML document.

3.7. CSS

CSS or Cascading Style Sheets is the W3C standard style and layout model for HTML. CSS allows web developers to control the style and layout of web pages. It tells the browser how to display various HTML elements, for example what will be font, color, size, alignment of a text or change the display of a button or text on hover. External Style sheets can be created and shared by multiple screens.

4. Different AJAX Formats for Data Transfer

AJAX can send and receive data from server in following formats

4.1. Text

As mentioned above in section 3.3, XMLHttpRequest object has a property called responseText which contains the text returned by Server.

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4) // communication with server is complete
{
document.employeeForm.name.value= xmlHttpRequest.responseText;
}
}

4.2. XML

responseXML property of the XMLHttpRequest contains an XML sent back by the Server

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4) // communication with server is complete
{
parseXML(xmlHttpRequest.responseXML); // we will create this method to parse the XML recieved
}
}

4.3. JSON (JavaScript Object Notion): Well, XML is a very powerful and universally accepted method of representing and handling data. But it is not a human readable format, JSON helps us here. It is a structured format in JavaScript to represent data. A simple example should help understanding; this is the same data which was represented in XML above

Var Employees=
{“Employee”: [
{“name”: “John”, “EmployeeNum”: “1234”, “Designation”: “PA”},
{“name”: “Eric”, “EmployeeNum”: “1232”, “Designation”: “SE”},
{“name”: “Tim”, “EmployeeNum”: “1233”, “Designation”: “PM”},
}

The complex string that is defined above is just an Array, so any information can be easily fetched like getting the name for first employee:

Employees.Employee[0].name;

If the JSON object is in string format, say sent back from server side, it is easy to convert to JSON object usong “eval” method

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4) // communication with server is complete
{
var jsonString = xmlHttpRequest.responseText;
var jsonObject= eval(‘(‘+jsonString+’)’);
}
}

The support for JSON is already available with most of server side programming languages.

5. Server Side Handling

If you look at the XMLHttpRequest object carefully, we are sending a URL in the open method. This URL defines the path to which the request being made is to be forwarded. This means AJAX itself is independent of server side languages. For example if we have an application in which XHR is calling a java servlet to retrieve some XML data, we can simply change the server side to PHP or dot Net by redirecting the URL to the new server. As far as the XML data sent back from that URL is same, AJAX application does not need to care about the server side languages.

Only consideration is that if you are using the XML as data format, then the server side language should have a good support for XML. In case of JSON, we need to take care that server side language has a good support for JSON objects, otherwise we will have to create parsers for the same.

6. A Basic Example

Here is a simple AJAX ‘Hello World’ example. It asks for the name of user, and clicking on the button in HTML page would bring the hello message from Server side without refreshing the page, so all the communication will be happening at the backend using AJAX.

Here is the HTML and JavaScript code.

<html>
<body>
<script type=”text/javascript”>
function ajaxExample()
{
var xmlHttpRequest;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest =new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttpRequest =new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttpRequest =new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(“Your browser does not support AJAX!”);
return false;
}
}
}

xmlHttpRequest.onreadystatechange=function()
{
if(xmlHttpRequest.readyState==4)
{
document.getElementById(“message”).innerHTML= xmlHttpRequest.responseText;
}
}

var name=document.getElementById(“name”).value;

xmlHttpRequest.open(“GET”,”test.jsp?name=”+name,true);
xmlHttpRequest.send(null);
}
</script>
<form name=”AJAXForm”>
Enter Your Name: <input type=”text” id=”name” name=”name” />
<input type=”Button”
onClick=”ajaxExample();” value=”ClickMe” />
<BR></BR>
A Message for you: <label id=”message” name=”message” >Check Here</label>
</form>
</body>
</html>

For this example we will keep a simple jsp file on the server side. The jsp will have following code

<jsp:directive.page contentType=”text/plain”/>

<%
String name=(request.getParameter(“name”)).toString();
String hello= “Hello “+ name;
out.print(hello);
%>

7. AJAX Advantages

* Better User Experience: One of the most important things for the web applications is user experience, as only a satisfied user will come back to your website. In case of AJAX, the user does not have to wait for server response and page refreshes which helps the pages to be more interactive.
* Optimized Bandwidth usage- Server does not have to send UI related information again and again, just the contents are sent. In many cases, related pages on a website consist of much content that is common between them. Using traditional methods, that content would have to be reloaded on every request. However, using Ajax, a web application can request only the content that needs to be updated, thus drastically reducing bandwidth usage and load time.
* No Special setup: Unlike Applets or Flash files, where you need to install plug-ins for running the applications, AJAX just need JavaScript enabled browser, which is common.
* Rich User Interfaces: The use of asynchronous requests allows the client’s Web browser UI to be more interactive and to respond quickly to inputs, and sections of pages can also be reloaded individually. Users may perceive the application to be faster or more responsive, even if the application has not changed on the server side.

8. AJAX Disadvantages

* No Standards as yet- The lack of a standards body behind Ajax means there is no widely adopted best practice to test Ajax applications.
* Back button not handled- Pages dynamically created using successive Ajax requests do not automatically register themselves with the browser’s history engine, so clicking the browser’s “back” button may not return the user to an earlier state of the Ajax-enabled page, but may instead return them to the last full page visited before it. Workarounds include the use of invisible IFrames to trigger changes in the browser’s history and changing the anchor portion of the URL (following a #) when AJAX is run and monitoring it for changes.
* Search Engines: Most of the search engines do not look for JavaScript code; hence the web applications using AJAX should provide an alternative means of accessing the content in order to get listed properly.
* Debugging: Debugging of JavaScript can be tougher than debugging any server side language.
* Security: You can view client-side JavaScript technology simply by selecting View Source from an Ajax-enabled HTML page. If we are handling any sensitive data in an AJAX application, that would show up with JavaScript. This needs to be taken care of while creating AJAX applications

Prototype.js library

Some of my old notes from Prototype (3-4 yrs older so there might be changes)

Overview

Prototype is a JavaScript toolkit. This helps in generation of a application by providing commonly used functionality so that the developer does not have to spend time on them.

The Prototype JS has features provides some basic functions which work as short cuts to already existing functionalities e.g. $() can be used in place of document.getElementById(), there are other complex functions for dealing with XMLHttpRequest. A many other libraries are created by extending this library.

You can download the free prototype.js from http://www.prototypejs.org/download. Once downloaded this JavaScript file can be added to any HTML page just like any other JavaScript file <script type=”text/javascript” src=”prototype.js”></script>

Key Functionalities

Let us look at some of the major functionalities provided by Prototype which makes life of developer simple.

$():

This is equivalent to saying document.getElemetById()
e.g.
var name=$(‘name’);

is same as
var name=document.getElementByID(‘name’);

Where HTML has
<input type= “text” id= “name” value= “John”/>

$$():

This will return you an array of elements from HTML document
e.g.
var eleArray= $$(“#formName input”);

This would return an array of all input type fields inside the form formName. This can be further used like

for(var i=0; i<eleArray.length; i++)
{
valueArray=eleArray[i].value;
}

$F():

To get the value of an element in the page
$F(‘name’) is equivalent to document.getElementByID(‘name’).value;

$A():

$A() Creates an array
var arrayOfNodes= $A(xmldoc.getElementsByTagName(‘abc’));

$H():

$H() Creates a hash table
var employeeHash= $H({
name: “John”,
email: “John@company.com”,
employeeId: “12345”
});

Try.these() Function:

This is an interesting function which lets developer write multiple functions. The code keep trying executing functions until one of them is success. This can be helpful if we are writing code to be supported by multiple versions of JavaScript or multiple browsers

Try.these(
function() {//do something
alert (“first one worked”);
return;
},
function() { // do something
alert (“second one worked”);
return;
}

AJAX Object:

Prototype provides AJAX object to minimize the effort using any AJAX related methods. AJAX object further provides the following classes.

AJAX.Request:

Ajax.Request object encapsulates the commonly used Ajax code for setting up the XMLHttpRequest object, performing cross-browser checking for compatibility and callback handling.

function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
onSuccess: process,
onFailure: function() {
alert(“There was an error with the connection”);
}
});
}

AJAX.Updater:

This is similar to the AJAX.Rrquest method above, with an additional feature that it can also update the page with the information returned by server to AJAX call.
new Ajax.Updater(container, url[, options])
function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
‘placeholder’,
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
}
});
}

AJAX.Responders:

AJAX responders are more of global methods which we register and unregister at the start and end of execution of code. They monitor all the AJAX activity going on and show the processing activities (say some animation while the data is being fetched from the server).
Ajax.Responders.register(attributes)
Ajax.Responders.unregister(attributes)
Some of the most common callbacks which are used with responders is
Ajax.Responders.register({
onCreate: showProcessing,
onComplete: hideProcessing
});

Additional Links

http://www.prototypejs.org/
http://www.sergiopereira.com/articles/prototype.js.html
http://attic.scripteka.com/prototype_cheatsheet_1.6.0.2.pdf
http://particletree.com/features/quick-guide-to-prototype/

AJAX with Java

As a major requirement for AJAX application from server side language is to retrieve the request from client side and then parse it based on the format of the request. The request can be in form of a simple string, or XML, or JSON. And similarly the AJAX application expects a response back from server in one of these formats. Java can fulfill these requirements easily.

As for the first part, the server side language needs to accept the request from AJAX application in client side. Now Java has multiple ways to accept the request like JSPs, Servlets, Struts, JSFs etc. lets take a Servlet example

Public void doGet(HttpServletRequest req, HttpServletResponse res)
{
String ajaxData=req.getParameter(“Data”);
String returnString = executeAJAXRequest(ajaxData);
res.setContentType(“text/xml”);
res.getWriter.write(returnString);
}

Above one is a simple example. I left some of the details on purpose. Like what is executeAJAXRequest method doing. This will actually depend on the kind of request we receive.

The request might be a text based one where we don’t need to do any special parsing.

String executeAJAXRequest(String name)
{
String helloString= “Hello “+name;
return helloString;
}

That’s just a simple example; we could be doing some database operations in the method based on the name we got. But the idea is that the data is being used as it is. If it was a number say employee number we would convert to long and use.

Now if the data is in XML format. We already know that Java has strong XML support. It can parse and create XML documents easily using either DOM or SAX parsers. The following example shows how to parse data (uses apache’s xerces library)

ajaxRequest=”<employees><employee><name>John</name></employee></employees>”;

ArrayList executeAJAXRequest(String ajaxRequest)
{
ArrayList<String> nameValueArray=new ArrayList<String>(10);
try
{
DOMParser parser = new DOMParser();

parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(ajaxRequest)));
DocumentImpl document = (DocumentImpl)parser.getDocument();

//get the root of the XML document
Node root = document.getFirstChild();
NodeList childNodes=root.getChildNodes();

for(int i=0;i<childNodes.getLength();i++)
{
nameValueArray.add(i, childNodes.item(i).getFirstChild().getFirstChild().getNodeValue());
}
}
catch (SAXException e)
{
e.printStackTrace();
//handle exception
}
catch(IOException e)
{
e.printStackTrace();
//handle exception
}

return nameValueArray;
}

The third way to pass data from client to server and vice versa is by using JSON. There are many libraries available in Java to parse and create JSON strings. Here is an example of code parsing a JSON String from client side using json-simple library (http://code.google.com/p/json-simple )

JSON string received from client is something like “{\”Employee\”: [{\”name\”: \”Eric\”, \”EmployeeNum\”: \”1232\”, \”Designation\”: \”SE\”}]}”

void executeAJAXRequest(String ajaxRequest)
{
JSONParser jsonParser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){

public List creatArrayContainer() {
//Add Details if required
return null;
}

public Map createObjectContainer() {
//Add Details if required
return null;
}
};

try{
Map jsonMap1 = (Map)jsonParser.parse(ajaxRequest, containerFactory);

Iterator iter1 = jsonMap1.entrySet().iterator();
while(iter1.hasNext()){
Map.Entry entry1 = (Map.Entry)iter1.next();
String valueString=entry1.getValue().toString();
String dataString=valueString.substring(1,valueString.length()-1);

Map jsonMap2 = (Map)jsonParser.parse(dataString, containerFactory);

Iterator iter2 = jsonMap2.entrySet().iterator();
System.out.println(“Here are the Employee Details”);
while(iter2.hasNext()){
Map.Entry entry2 = (Map.Entry)iter2.next();
System.out.println(entry2.getKey() + “=>” + entry2.getValue());
}
}

}
catch(ParseException pe){
System.out.println(pe);
}
}

ZK framework: AJAX without JavaScript

Recently came across ZK framework which can be used to create AJAX based UI without actual JavaScript code. It claims that you do not need to be a programmer to code using ZK framework which actually uses ZUML Markup language to do create the UI. I have not used it yet but look interesting and would like to give it a try.

http://en.wikipedia.org/wiki/ZK (framework)

http://www.zkoss.org/

jQuery error- simpleLightbox not found

Faced a unique error with jQuery today.  I was using jquery-1.3.2.min.js and jquery-simplelightbox.js. Which were included properly in the jsp file, but still the javascript was throwing the error that simpleLightbox function is not found.

on a close look it was found that after adding both the JS files, an additional jsp file was added which was again adding jquery-1.3.2.min.js, hence overriding the original jQuery object.

Lesson learnt- Always make sure that jQuery js file is added only once, especially if we are modifying the object.

Object Oriented JavaScript- 4

We have talked about Basic OO concepts, Objects and Classes, and Inheritance in JS. Today, let me look at polymorphism in JS.

Now polymorphism is a criteria which can help me create multiple method with the same name, with the program deciding at the run time, that which method to be called, based on signature of the method. The signature of methods can differ by number of arguments it takes, or type of arguments. In Js, we can not differentiate between methods based on type of arguments, because every type in JS can be treated as type ‘var’. But yes, JS supports polymorphism using different number of arguments, though indirectly.

In a way, polymorphism in JS is simpler than in OO languages. In JS you don’t even need to create multiple methods, in the same method, you can have different handlers for different number of arguments. arguments.length does the trick for you. Enough of talking, here is your example

<script language=”JavaScript”>
//trying to create a closed figure

function closedFigure()
{

this.createFigure=function()
{
var length = arguments.lengt
h;
if(length<3) { alert("atleast 3 sides are required to close the figure"); } if(length==3) { alert("you are trying to create a triangle with "+ arguments[0]+","+arguments[1]+","+arguments[2]); } if(length==4) { alert("you are trying to create a quadrilateral with "+arguments[0]+","+arguments[1]+","+arguments[2]+","+arguments[3]); } if(length==5) { alert("you are trying to create a pentagon with "+arguments[0]+","+arguments[1]+","+arguments[2]+","+arguments[3]+","+arguments[4]); } } } var figure=new closedFigure(); figure.createFigure(1,2); figure.createFigure(1,2,3); figure.createFigure(1,2,3,4); figure.createFigure(1,2,3,3,5); </script>

Object Oriented JavaScript -3

In the last post I talked about how to create objects and classes in JS. The next step is to go for Inheritance.

Continuing from our previous examples, let’s say you want to create a class for rectangle

function rectangle(length, breadth)
{
this.length=length;
this.breadth=breadth;
this.area=setArea;
this.perimeter=setPerimeter;
this.test=function()
{
alert("hi! you are in test function");
}

function setArea()
{
return (this.length*this.breadth);
}

function setPerimeter ()
{
return 2*(this.length+this.breadth);
}
}

let’s save the above code in a file called rectangleScript.js

Now there is a HTML file where you want to use this JS file code. You will simply add

<script type=”text/javascript” src=”rectangleScript.js” language=”javascript”></script>

Next let’s say you want to add some properties and methods to this already existing class. The ‘prototype’ keyword of Java comes into help here.

<script type="text/javascript" src="rectangleScript.js" language="javascript"></script>
<script language="JavaScript">
rectangle.prototype.color="red";
rectangle.prototype.setColor=function(color)
{
this.color=color;
}

rectangle.prototype.isSquare=function()
{
if(this.length==this.breadth)
return true;
else
return false;
}

var rec=new rectangle(2,6);
alert("area here:"+rec.area());
alert("is it a square:"+rec.isSquare());

alert("color:"+rec.color);
rec.setColor("yellow");
alert("color:"+rec.color);

var rec1=new rectangle(3,3);
alert("area here:"+rec1.area());
alert("is it a square:"+rec1.isSquare());
alert("color:"+rec1.color);

</script>

You might still argue that we have not actually inherited a class by another class, this is just adding properties. Yes, even inheriting a class by another is possible in JS. Again prototype keyword is the magic word. Additionally, we will see how method overloading works with JS. Look at this example

<script type="text/javascript" src="rectangleScript.js" language="javascript"></script>

<script language="JavaScript">

function goldenRectangle(length, breadth, someProperty)
//rectangle with length/ breadth=1.618
{
//this.rectangle=new rectangle(length, breadth);

this.length=length;
this.breadth=breadth;
this.newProperty=someProperty;
}

goldenRectangle.prototype =new rectangle();

//Method Overloading

goldenRectangle.prototype.test=function()
{
alert("hi! you are in goldenRectangles test function");
}

var myGoldenRectangle=new goldenRectangle(10,6,1);
alert("area:"+myGoldenRectangle.area());
alert("test property:"+myGoldenRectangle.newProperty);
myGoldenRectangle.test();
</script>

Object Oriented JavaScript -2

Continuing from my first post about this topic, where I mentioned why we need OO JS. First of all let me see what do we picture the moment we say that a language is OO. Here are some basic necessities of OO
Encapsulation: Usage of Classes and Objects
Inheritance: Extending Classes, Overloading methods
Polymorphism: Same method with different number of arguments

Now without wasting further time, lets get on with how these OO principles can be applied to JS

Creating Objects in JS

1. Using Inbuilt Object type:

var myRectangle=new Object();
myRectangle.length=2;
myRectangle.breadth=4;

myRectangle.area=function()
{
return (myRectangle.length*myRectangle.breadth);
}

alert(“area:”+myRectangle.area());

2. The JSON (JavaScript Object Notion) way
var myRectangle2={
length:2,
breadth:4,
area:function()
{
return(this.length*this.breadth);
}
};

alert(“area2:”+myRectangle2.area());

Creating Classes in JS

You might argue that so far we have only created Objects, but in an OO language we first create a class and then create object. Well, that is very much possible in JS as well.

The good news is, that in JS, functions can be treated as classes. How? Let’s check this example.

//Creating a class in JS
function rectangle(length, breadth)
{
this.length=length;
this.breadth=breadth;
this.area=setArea;
this.perimeter=setPerimeter;

this.test=function()
{
alert(“hi! you are in test function”);
}

function setArea()
{
return (this.length*this.breadth);
}

function setPerimeter ()
{
return 2*(this.length+this.breadth);
}
}

var rec=new rectangle(2,6);
var areahere=rec.area();
alert(areahere);
alert(rec.perimeter());

var rec1=new rectangle(1,1);
var areahere=rec1.area();
alert(areahere);
alert(rec1.perimeter());
rec1.test();

More on OO JS (Inheritance and Polymorphism) later

Object Oriented JavaScript

Here are some notes from presentation I have recently given on Object Oriented JS (JavaScript)

Why do we need OO(Object Oriented) JS?

With the popularity of AJAX and similar technologies, role of JS has become relatively more important in Web applications. Earlier you could think of JS just as a facilitator for the actual web application. But now, a lot of coding is being done in JS, sometimes even more than 50% of the code is handled in JS. With more emphasis on usability and look and feel of the application, JS has taken center stage for web applications.

Another reason for JS popularity is because it is easy to code. You don’t need a special training for JS as with other languages like Java. This is because JS was originally meant for designers rather than developers. Now, because it is easy to code, it is easy to mess up too. You don’t have proper structure enforced while coding for JS. That is why need of properly structured OO JS is felt more now.

In addition to above stated reasons, one more concern with JS is that it is highly underused, there are a lot of functionality JS provides you which you don’t use (in many cases we are not even aware of a lot of possibilities JS has)

Traditional Usage of JS
For sake of simplicity, let me take an example where we try to calculate area of rectangle and a square. In traditional usage of JS, we will initially create a JS file and keep adding methods as per our requirements (mostly the JS files ends up in a mess)

Say initially you wanted a method to calculate area of rectangle, you created a method called area, then you wanted to calculate perimeter of teh same rectangle, and you added another method. Sometime later you want to calculate area of square. and so on

<script language=”JavaScript”>

//creating method for calculating rectangle area
function area(length, breadth)
{
return length*breadth;
}

var myArea=area(2,3);
alert(“area is :”+myArea);

//add a method for calculating perimeter
function perimeter(length, breadth)
{
return 2*(length+breadth);
}

var myPerimeter=perimeter(2,3);
alert(“myPerimeter is :”+myPerimeter);

//creating method for calculating square area
function square_area(side)
{
return side*side;
}

var myArea2=square_area(2,3);
alert(“square area is :”+myArea2);
</script>

Now my question is.. is this how we do code in any OO language like Java?

Nope. We will create our classes. We will use polymorphism. We will properly organize our code.

If you are already aware of what I am talking about, you can stop reading. If not, come back tomorrow, I will write more about it.

(..to be continued)

Toolkit vs Framework (and AJAX)

Toolkit vs Framework:
If you go through some websites which talk about frameworks and toolkits, especially in AJAx context, you will feel the term framework and toolkit has been used interchangeably. Though just by looking at the two terms we can make out the difference, a toolkit is something which will provide you with some tools or methods which will help you achieve your goal, whereas a framework is something that provides you a way in which the application should be created. But when it comes to AJAX, there is not much difference as the same thing can do both these work. Moreover at times you will also find the usage of term library, which is actually just a collection of methods. A toolkit would be a collection of these libraries, but again sometimes we might just have one library in the toolkit.