Archive

Archive for the ‘AJAX’ Category

Object Oriented JavaScript- 4

August 12th, 2009

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>

kamal AJAX, DOM, JavaScript

Object Oriented JavaScript -3

August 6th, 2009

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>

kamal AJAX, DOM, JavaScript

Object Oriented JavaScript -2

August 4th, 2009

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

kamal AJAX, DOM, JavaScript

Object Oriented JavaScript

July 29th, 2009

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)

kamal AJAX, DOM, JavaScript

Toolkit vs Framework (and AJAX)

June 25th, 2009

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.

kamal AJAX

AJAX: is it Asynchronous JavaScript and XML?

June 9th, 2009

Recently one of friends asked me how to learn AJAX? Is it all about JavaScript and XML and sending asynchronous data? Though the term AJAX stand for Asynchronous JavaScript and XML. That means 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

kamal AJAX

Difference between visibility hidden vs display none

June 5th, 2009

I spent almost an entire day on this, so wanted to share the information in case it might be helpful for others. We at times need to remove a DOM object (textbox/ label/ dropdown etc) from the UI. For which we use two things object.style.visibility=”hidden” and object.style.display=”none”. Though both of them can remove the object from UI, yet there is a significant difference between these two approaches. Whereas visibility hidden will “hide” the object, it will still leave the object on the UI (in hidden format). On the other hand display=”none” will completely remove the object from UI.

The differentiation is more important in a case, where the css being used here does not specify the x and y coordinates for DOM objects, it instead places one object after another. So the trick here is, if I make an object invisible by hiding it (visibility=”hidden”), it will still occupy that one space in the flow, and a blank cell will appear on the screen. Whereas if display is none, then the next object will take place of this object and hence no empty spaces are shown on the screen.

So both the approaches can be used as per ones requirement

kamal AJAX, DOM, Design, JavaScript, coding

Google Web Toolkit

May 9th, 2009

Sometime back I spent some time to figure our how to use GWT for one of my projects. Here are some notes from that-

The magic with GWT is that we are provided with a Java to JavaScript Compiler which takes your Java code and creates JavaScript out of it. Additionaly GWT provides us with various libraries to help us develop the web pages and behavior using Java.

The trick here is, that GWT works is two modes. Hosted mode and Web Mode

Hosted Mode: Here, your Java application is working. The GWT browser takes your Java code, interpret it and show it as it would appear in the web page. As we are just running the Java code, this is where we can debug our application just as a java app. And we already know debugging java is much easier than debugging JavaScript, hence life is simple.

Web Mode: When we are done with the Java application creation, we run it on Web Mode. GWT’s Java to JavaScript Compiler gives us JS and HTML pages which we can directly deploy and user need not know how they were created.

Let’s get started

Step 0: Prerequisite

Download GWT from http://code.google.com/webtoolkit/download.html and unzip.
(that’s all)

Step 1: Creation Project:
GWT comes with command line utilities which help us create a project and application

projectCreator -eclipse TestProject

applicationCreator -eclipse TestProject com.test.client.TestApplication

Eclipse keyword in above command shows that I am using eclipse IDE, which has special support with GWT. If you are using some other IDE, just remove this keyword.

Step 2: Copy all the newly created files to a folder. Open Eclipse and import this project

Step 3: Right Click TestApplication.java, RunAS, Run, Java Application, check the main class is shown as com.google.gwt.dev.GWTShell, click run
This will open up GWT development shell and will show you the demo web application. A button you click and get the Welcome Message.

This demo application is running from TestApplication java code. You can get into this file and play around. You will find classes like panels, dialoguebox, buttons etc. You can try and make changes to the web page that is appearing.

Time to convert the Java code to JS and HTML.

Simple-just click TestApplication-compile.cmd. this will create two more folders in project tomcat and www. Tomcat has server related info (web.xml) and www has all the web pages, css, JS etc.

But this example is totally JS. Now how to make our code communicate with Java Code. One simple method is RPC. Here is a simple example in continuation to the prev one. Let’s say the welcome message needs to show name as well for the user. Lets write a backend class which will send this name. Here I will hardcode the name, in real application it can be read from database.

1: Create two interfaces under existing com.test.client package
i. GetNameService

package com.test.client;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath(”gettingName”)
public interface GetNameService extends RemoteService {
}

GetNameServiceAsync

package com.test.client;
import com.google.gwt.user.client.rpc.AsyncCallback;

public interface GetNameServiceAsync {
void getName(AsyncCallback callback);
}
2: Goto TestApplication.gwt.xml under src->com.test and add this line

<servlet path=”/gettingName” class=”com.test.server.GetNameServiceImpl” />

3: Create a new Package com.test.server and add the server side class

package com.test.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.test.client.GetNameService;

public class GetNameServiceImpl extends RemoteServiceServlet implements
GetNameService {
public String getName()
{
File afile=new File(”C:\\file.txt”);
String name=”";
System.out.println(”name”);

try {
BufferedReader input = new BufferedReader(new FileReader(afile));
name=input.readLine();
System.out.println(”name now:”+ name);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(”return name:”+ name);
return name;
}
}

4: Goto Test Application and Add this method

private void getNameNow() {
// Initialize the service proxy.
if (getNameService == null) {
getNameService = GWT.create(GetNameService.class);
}

// Set up the callback object.
AsyncCallback callback = new AsyncCallback () {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
}

public void onSuccess(String result) {
name=result;
}
};

// Make the call to the stock price service.
getNameService.getName(callback);
}

}

And change addClickListener to look like
button.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
getNameNow();
dialogBox.setText(”Welcome to GWT! “+name);
dialogBox.center();
dialogBox.show();
}

All set, now run the application again. Change the name in text file and you will see the changed name in your application.

kamal AJAX

AJAX I18N

April 28th, 2009

DWR: Direct Web Remoting

April 14th, 2009

Notes from my Recent Research on DWR

DWR is an open source Java library which helps client side AJAX code to call and use Server side Java code as if it is available locally. The communication can be two way, on one hand, JavaScript can call Java methods and on the other hand Java can call JavaScript methods (Reverse AJAX)

For getting started download the latest jar from http://directwebremoting.org/dwr/download

DWR consists of two main parts:
A Java Servlet running on the server that processes requests and sends responses back to the browser.

Let’s create a simple DWR application.

Step1: Add these lines to web.xml

<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>


<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

Step 2: Create dwr.xml

<!DOCTYPE dwr PUBLIC
“-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN”
“http://getahead.org/dwr/dwr20.dtd”>

<dwr>
<allow>
<create creator="new" javascript="JDate">
<param name="class" value="java.util.Date"/>
</create>
<create creator="new" javascript="Employee">
<param name="class" value="testPkg.EmployeeBean"/>
</create>
</allow>
</dwr>

Step 3. Create EmployeeBean. Java

package testPkg;

public class EmployeeBean {

private static String name;
private static String EmployeeNum;
private static String Address;

public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmployeeNum() {
return EmployeeNum;
}
public void setEmployeeNum(String employeeNum) {
EmployeeNum = employeeNum;
}
public String getName() {
System.out.println(”return:”+name);
return name;
}
public void setName(String name) {
System.out.println(”called with:”+name);
this.name = name;
System.out.println(”now:”+this.name);
}
}

Step 4: Here is the final HTML code (change the path for JS files as per the project)

<html>
<head>
<script type='text/javascript'
src='/[Path]/dwr/interface/Employee.js’></script>
<script type=’text/javascript’ src=’/[Path]/dwr/engine.js’></script>
<script type=’text/javascript’ src=’/[Path]/dwr/util.js’></script>
</head>
<body>
First Set the Employee Name:
<input type=”textbox” id=”setname” value=”Name Here” />
<input type=”button”
onclick=’Employee.setName(document.getElementById(”setname”).value, reply8);’
value=”Set Name” />
<script type=’text/javascript’>
var reply8 = function(data)
{
if (data != null && typeof data == ‘object’) alert(dwr.util.toDescriptiveString(data, 2));
else alert(”data set!”);
}
</script>
<br></br>
<input type=’button’ onclick=’Employee.getName(reply);’ value=’Get Name’
title=’Calls Employee.getName(). View source for details.’ />
<script type=’text/javascript’>
var reply = function(data)
{
if (data != null && typeof data == ‘object’) alert(dwr.util.toDescriptiveString(data, 2));
else alert(”set data was: “+data);
}
</script>
</body>
</html>

Now go to your dwr.html and see the magic

http://directwebremoting.org/

kamal AJAX