Category Archives: AJAX

AJAX: is it Asynchronous JavaScript and XML?

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

Difference between visibility hidden vs display none

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

Google Web Toolkit

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.

DWR: Direct Web Remoting

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/