Search the Web:

Google

Monday, January 28, 2008

Ajax Principles

Michael Mahemoff a software developer and usability expert, identified several key principles of good Ajax applications that are worth repeating:

Minimal traffic: Ajax applications should send and receive as little information as possible to and from the server. In short, Ajax can minimize the amount of traffic between the client and the server. Making sure that your Ajax application doesn't send and receive unnecessary information adds to its robustness.

No surprises: Ajax applications typically introduce different user interaction models than traditional web applications. As opposed to the web standard of click-and-wait, some Ajax applications use other user interface paradigms such as drag-and-drop or double-clicking. No matter what user interaction model you choose, be consistent so that the user knows what to do next.

Established conventions: Don't waste time inventing new user interaction models that your users will be unfamiliar with. Borrow heavily from traditional web applications and desktop applications so there is a minimal learning curve.

No distractions: Avoid unnecessary and distracting page elements such as looping animations, and blinking page sections. Such gimmicks distract the user from what he or she is trying to accomplish.

Accessibility: Consider who your primary and secondary users will be and how they most likely will access your Ajax application. Don't program yourself into a corner so that an unexpected new audience will be completely locked out. Will your users be using older browsers or special software? Make sure you know ahead of time and plan for it.

Avoid entire page downloads: All server communication after the initial page download should be managed by the Ajax engine. Don't ruin the user experience by downloading small amounts of data in one place, but reloading the entire page in others.

User first: Design the Ajax application with the users in mind before anything else. Try to make the common use cases easy to accomplish and don't be caught up with how you're going to fit in advertising or cool effects.

The common thread in all these principles is usability. Ajax is, primarily, about enhancing the web experience for your users; the technology behind it is merely a means to that end. By adhering to the preceding principles, you can be reasonably assured that your Ajax application will be useful and usable.

Sunday, January 27, 2008

How Http Communication Works

The driving force behind Ajax is the interaction between the client (web browser) and the server. Previously, the understanding of this communication was limited to those who developed purely on the server-side using languages such as Perl and C. Newer technologies such as ASP.NET, PHP, and JSP encouraged more of a mix of client- and server-side techniques for software engineers interested in creating web applications, but they often lacked a full understanding of all client-side technologies (such as JavaScript). Now the pendulum has swung in the other direction, and client-side developers need to understand more about server-side technology in order to create Ajax solutions.

HTTP PRIMER

Central to a good grasp of Ajax techniques is hypertext transmission protocol (HTTP), the protocol to transmit web pages, images, and other types of files over the Internet to your web browser and back. Whenever you type a URL into the browser, an "http://" is prepended to the address, indicating that you will be using HTTP to access the information at the given location.

HTTP consists of two parts: a request and a response. When you type a URL in a web browser, the browser creates and sends a request on your behalf. This request contains the URL that you typed in as well as some information about the browser itself. The server receives this request and sends back a response. The response contains information about the request as well as the data located at the URL (if any). It's up to the browser to interpret the response and display the web page (or other resource).

HTTP Requests

The format of an HTTP request is as follows:
<request-line>
<headers>
<blank>
[<request-body>]

In an HTTP request, the first line must be a request line indicating the type of request, the resource to access, and the version of HTTP being used. Next, a section of headers indicate additional information that may be of use to the server. After the headers is a blank line, which can optionally be followed by additional data (called the body).

There are a large number of request types defined in HTTP, but the two of interest to Ajax developers are GET and POST. Anytime you type a URL in a web browser, the browser sends a GET request to the server for that URL, which basically tells the server to get the resource and send it back. Here's what a GET request for http://www.example.com/ might look like:

GET / HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive

The first part of the request line specifies this as a GET request. The second part of that line is a forward slash (/), indicating that the request is for the root of the domain. The last part of the request line specifies to use HTTP version 1.1 (the alternative is 1.0). And where is the request sent? That's where the second line comes in.

The second line is the first header in the request, Host. The Host header indicates the target of the request. Combining Host with the forward slash from the first line tells the server that the request is for www.example.com/. (The Host header is a requirement of HTTP 1.1; the older version 1.0 didn't require it.) The third line contains the User-Agent header, which is accessible to both server- and client-side scripts and is the cornerstone of most browser-detection logic. This information is defined by the browser that you are using (in this example, Firefox 1.0.1) and is automatically sent on every request. The last line is the Connection header, which is typically set to Keep-Alive for browser operations (it can also be set to other values, but that's beyond the scope of this book). Note that there is a single blank line after this last header. Even though there is no request body, the blank line is required.


If you were to request a page under the http://www.example.com/ domain, such as http://www.example.com/books, the request would look like this:
GET /books/ HTTP/1.1
Host: http://www.example.com/
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive

Note that only the first line changed, and it contains only the part that comes after http://www.example.com/ in the URL.
Sending parameters for a GET request requires that the extra information be appended to the URL itself. The format looks like this:
URL ? name1=value1&name2=value2&..&nameN=valueN

This information, called a query string, is duplicated in the request line of the HTTP request, as follows:
GET /books/?name=ajax%20book HTTP/1.1
Host: http://www.example.com/
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Connection: Keep-Alive

Note that the text "ajax book" had to be encoded, replacing the space with %20, in order to send it as a parameter to the URL. This is called URL encoding and is used in many parts of HTTP. (JavaScript has built-in functions to handle URL encoding and decoding; these are discussed later in the chapter). The name-value pairs are separated with an ampersand. Most server-side technologies will decode the request body automatically and provide access to these values in some sort of logical manner. Of course, it is up to the server to decide what to do with this data.

The POST request, on the other hand, provides additional information to the server in the request body. Typically, when you fill out an online form and submit it, that data is being sent through a POST request.
Here's what a typical POST request looks like:
POST / HTTP/1.1
Host: http://www.example.com/
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
Gecko/20050225 Firefox/1.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
Connection: Keep-Alive
name=ajax%20book&publisher=smrithi

You should note a few differences between a POST request and a GET request. First, the request line begins with POST instead of GET, indicating the type of request. You'll notice that the Host and User-Agent headers are still there, along with two new ones. The Content-Type header indicates how the request body is encoded. Browsers always encode post data as application/x-www-form-urlencoded, which is the MIME type for simple URL encoding. The Content-Length header indicates the byte length of the request body. After the Connection header and the blank line is the request body. As with most browser POST requests, this is made up of simple name-value pairs, where name is Professional Ajax and publisher is Wiley. You may recognize that this format is the same as that of query string parameters on URLs.
As mentioned previously, there are other HTTP request types, but they follow the same basic format as GET and POST. The next step is to take a look at what the server sends back in response to an HTTP request.


HTTP Responses

The format of an HTTP response, which is very similar to that of a request, is as follows:
<status-line>
<headers>
<blank line>
[<response-body>]

As you can see, the only real difference in a response is that the first line contains status information instead of request information. The status line tells you about the requested resource by providing a status code. Here's a sample HTTP response:

HTTP/1.1 200 OK
Date: Sat, 31 Dec 2005 23:59:59 GMT
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 122

<html>
<head>
<title>Example Homepage</title>
</head>
<body>
<!-- body goes here -->
</body>
</html>

In this example, the status line gives an HTTP status code of 200 and a message of OK. The status line always contains the status code and the corresponding short message so that there isn't any confusion. The most common status codes are:

200 (OK): The resource was found and all is well.

304 (NOT MODIFIED): The resource has not been modified since the last request. This is used most often for browser cache mechanisms.

401 (UNAUTHORIZED): The client is not authorized to access the resource. Often, this will cause the browser to ask for a user name and password to log in to the server.

403 (FORBIDDEN): The client failed to gain authorization. This typically happens if you fail to log in with a correct user name and password after a 401.

404 (NOT FOUND): The resource does not exist at the given location.

Following the status line are some headers. Typically, the server will return a Date header indicating the date and time that the response was generated. (Servers typically also return some information about themselves, although this is not required.) The next two headers should look familiar as well, as they are the same Content-Type and Content-Length headers used in POST requests. In this case, the Content-Type header specifies the MIME type for HTML (text/html) with an encoding of ISO-8859-1 (which is standard for the United States English resources). The body of the response simply contains the HTML source of the requested resource (although it could also contain plain text or binary data for other types of resources). It is this data that the browser displays to the user.
Note that there is no indication as to the type of request that asked for this response; however, this is of no consequence to the server. It is up to the client to know what type of data should be sent back for each type of request and to decide how that data should be used.

Thursday, January 10, 2008

What Sets Ajax Apart - Difference between Ajax and other technologies

While CSS, DOM, aynchronous requests and Javascript are all necessary components of Ajax, it is quite possible to use all of them without doing Ajax.
In a classic web application when compared to its Ajax counterpart, the user workflow is defined by code on the server and the user moves from one page to another, punctuated by the reloading of the entire page. During these reloads, the user cannot continue with his work. In an Ajax application, the workflow is at least partly defined by the client application, and contact is made with the server in the background while the user gets on with his work.
In between these extremes are many shades of gray. A web application may deliver a series of discrete pages following the classic approach, in which each page cleverly uses CSS, DOM, JavaScript and asynchronous request objects to smooth out the user's interaction with the page, followed by an abrupt halt in productivity while the next page loads. A JavaScript application may present the user with page-like pop-up windows that behave like classic web-pages at certain points in the flow. The web browser is a flexible and forgiving environment and Ajax and non-Ajax functionality can be intermingled in the same application.
What sets Ajax apart is not the technologies that it employs but the interaction model that it enables through the use of those technologies. The web-based interaction model to which we are accustomed is not suited to sovereign applications and new possibilities begin to emerge as we break away from that interaction model.
There are atleast two levels at which Ajax can be used - and several positions between these as we let go of the classic page-based approach. The simplest strategy is to develop Ajax-based widgets that are largely self-contained and that can be added to a web page with a few imports and script statements. Stock tickers, interactive calendars, and chat windows might be typical of this sort of widget. Islands of application-like functionality are embedded into a document-like web page. Most of the Google's current forays into Ajax fit this model. The drop-down box of Google Suggest and the map widget in Google Maps are both interactive elements embedded into a page.
If we want to adopt Ajax more adventurously, we can turn this model inside out, developing a host application in which application-like and document-like fragments can reside. This approach is more analogous to a desktop application or even a window manager or desktop environment. Google's gmail fits this model, with individual messages rendering as documents within an interactive, application-like superstructure.
In some ways, learning the technologies is the easy part. The interesting challenge in developing with Ajax is in learning how to use them together. We are accustomed to thinking of web applications as storyboards, and we shunt the user from one page to another following a pre-determined script. With the application-like functionality in our web application, we can provide the user with a more fine-grained handle on the business domain, which can enable a more freee-form problem solving approach to his work.

Wednesday, January 9, 2008

Why Ajax for Greater Design

When it comes to web applications, AJAX offers two crucial advantages:

  • It is efficient: only a part of the web page that needs to be modified is being modified. With traditional server-side scripting you send the entire new page to the browser.
  • It is lightweight: only small amounts of data (in the XML form) are being exchanged through the Internet, making your web applications very fast.

How to retrieve static data dynamically

If your web page needs data that is already available (in a file) and does not need to be assembled, here is what to do:

  • Place the data in a .js file, and
  • Use the loadScript() function below to dynamically load and use the .js file you need

function loadScript(scriptURL){

var newScript = document.createElement("script");

newScript.src = scriptURL;

document.body.appendChild(newScript);

}

The loaded script runs immediately in the document context, allowing you to modify page elements as needed.

Lets see the example. First the html file. Save this as Example1.html

<html>

<head>
<title>AJAX Tutorial: Example 1

</title>

<script language="JavaScript" src="ajax.js">

</script>
<script language="JavaScript">

function doSomethingWithData(str){

document.getElementById('MyID').innerHTML = str;

}
</script>

</head>
<body>

<h1>AJAX Tutorial: Example 1

</h1> This example shows how to dynamically retrieve data from a JavaScript file.

<br>

<br>

<input type="button" value="Data file #1" onclick="loadScript('Data1.js')" />

<input type="button" value="Data file #2" onclick="loadScript('Data2.js')" />

<input type="button" value="Data file #3" onclick="loadScript('Data3.js')" />

<p>

<div id="MyID">&nbsp;

</div>

</p>

</body>

</html>

Now, the ajax code in ajax.js file

function loadScript(scriptURL){

var newScript = document.createElement("script");

newScript.src = scriptURL;

document.body.appendChild(newScript);}
function loadData(URL){

// Create the XML request

xmlReq = null; if(window.XMLHttpRequest)

xmlReq = new XMLHttpRequest();

else if(window.ActiveXObject) xmlReq = new ActiveXObject("Microsoft.XMLHTTP");

if(xmlReq==null) return;

// Failed to create the request
// Anonymous function to handle changed request states

xmlReq.onreadystatechange = function() {

switch(xmlReq.readyState) {

case 0: // Uninitialized

break;

case 1: // Loading

break; case 2:

// Loaded

break; case 3: // Interactive

break;

case 4: // Done!

// Retrieve the data between the tags

doSomethingWithData(xmlReq.responseXML.getElementsByTagName('quote')[0].firstChild.data);

break;

default:

break;

}

}
// Make the request

xmlReq.open ('GET', URL, true); xmlReq.send (null);

}

In the Example1.html, we create 3 buttons to get the information in that file on to the page, those files are named as Data1.js, Data2.js and Data3.js

Save the below code as Data1.js

doSomethingWithData("Life is like a dogsled team. If you ain't the lead dog, the scenery never changes (Lewis Grizzard)");

Save the below code as Data2.js

doSomethingWithData("Anyone can steer the ship when the sea is calm (Publilius Syrus)");

Save the below code as Data3.js

doSomethingWithData("A leader is a dealer in hope (Napoleon Bonaparte)");

To better understand what is going on, let us examine all the files being used.

The function loadScript is stored in the ajax.js file. As soon as the specified script file has been loaded, the script inside it is executed. The Data1.js file is used to store or compute the data requested. For simplicity, it only has one line of code:

When the first button is clicked, it calls loadScript('Data1.js'), whick loads and then executes the script in Data1.js. This script passes the data as a parameter to doSomethingWithData (str), which is defined in Example1.htm. In our example, the data is displayed by modifying the div "MyID".

How to retrieve dynamic data dynamically

In many cases, the data is not readily available and must be assembled by a process or from a database. JavaScript does this by using XMLHttpRequest and receiving the content of an xml file in response.
The xml file can then be processed and used to modify various elements on your web page, which is illustrated in Example 2.

Save the html file as Example2.html

<html>

<head>

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

</script>
<script language = "JavaScript">

<!--// Function to call with the data retrieved from the XML file function doSomethingWithData(datastr) {

document.getElementById('MyID').innerHTML = datastr;

}//-->

</script>
<title>AJAX Tutorial: Example 2

</title>

</head>

<body>

<h1>AJAX Tutorial: Example 2

</h1> This example shows how to dynamically retrieve data from an XML file. Note: have your web server running on your local machine, or place the example on the web.

<br>

<br>

<input type="button" value="Load data.xml" onclick="loadData('data.xml');" />

<p> <div id="MyID">&nbsp;

</div>

</p>

</body>

</html>

Next take the actual xml file and save it as data.xml

<?xml version="1.0" encoding="utf-8"?>

<root>

<quote>Silence is foolish if we are wise, but wise if we are foolish (Charles Colton)</quote>

</root>

Data.xml is a simple data file. In this example, we are retrieving the data between the <quote> .. </quote> tags. The ajax.js file contains the loadData (URL) function, which does most of the work. The loadData() function creates and then makes the XML request. For the sake of simplicity, the URL is the xml file itself (our Data.xml). In more complex applications, the URL could be a call to a php, asp, or some other process responsible for assembling and returning the XML data. Observe the line xmlReq.onreadystatechange = function(): it defines an anonymous function (in this case) to call whenever the readyState shanges. Here we only process the case when the script is fully loaded: responseXML holds the received XML file, and xmlReq.responseXML.getElementsByTagName retrieves the part of it we are interested in. Similar to our previous example, this script passes the data as a parameter to doSomethingWithData(str), which is defined in Example2.html.

When the button is clicked, it makes a loadData() call to the process that will return the data in the form of an XML file. When the file is fully loaded, doSomethingWithData() is called to process the results. The whole process is illustrated below:
Web browser -> AJAX application -> XML request -> server-side process -> XML file generated -> XML file sent back to XML request -> onreadystatechange received by AJAX application -> data from XML file retrieved/processed -> web browser displays results


Monday, January 7, 2008

Ajaxifying a Web Application - Auto-population of Data

To start, let’s take a look at the source code for a form that a customer must fill in:

<html>
<head>
<title>Customer Data Screen</title>
</head>
<body>
<h1>Corporate System</h1>
<h2>Enter Customer Data</h2>
<table>
<tr>
<th>Customer Name:</th>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<th>Address:</th>
<td>
<input type="text" name="address"/>
</td>
</tr>
<tr><th
>City:</th><td>
<input type="text" name="city"/>
</td>
</tr>
<tr><th>State:</th><td>
<input type="text" name="state"/>
</td>
</tr>
<tr>
<th>Zip:</th><td>
<input type="text" name="zip"/>
</td></tr>
<tr>
<th></th>
<td><input type="Submit" value="Add Customer"/>
</td>
</tr>
</table>
</body>
</html>

We want to add behavior so that when the user enters a value in the Zip field, we’ll send the ZIP code to the server, receive a response containing the city and state that correspond to the ZIP, and populate the City and State fields with those values.

Preparing the HTML
The first step towards this end will be to add an event handler to the event handler Zip <input> tag. Event Handlers in HTML allow you to execute script code in the web page when certain user interactivity or browser tasks occur. Secondly, we’ll have to add id= attributes to the City and State <input> elements. Our revised <input> elements look like this (with the surrounding table rows shown for context):

<tr>
<th>Zip:</th><td><input onblur="getZipData(this.value)"type="text" name="zip"/>
</td>
</tr>
<tr>
<th>City:</th><td><input id="city" type="text" name="city"/>
</td>
</tr>
<tr>
<th>State:</th><td><input id="state" type="text" name="state"/>
</td>
</tr>

The event handler is registered via the onblur= attribute, which in this case specifies that the script function named getZipData( ) will be invoked when the focus leaves this element. The parameter passed to this function, this.value, specifies that the value property of the <input> element will be passed; the this is a reference to the element on which the event handler has been registered.
We’ve also changed the ordering of the table rows; now the Zip input comes first. While this new layout is atypical for American addresses, it reflects a more natural flow for the ajaxified version of the screen, since entering the ZIP code will auto-populate the other two fields beneath it.

Communicating with the Server

We’re now done with the first half of our task: wiring the HTML to a script that will perform our Ajax behavior. Now we need to tackle the slightly trickier second bit: writing the script. The key to Ajax is a JavaScript object called XMLHttpRequest, the engine that can send HTTP requests, receive responses, and parse them as XML. Let’s create our getZipData( ) function, which will create an instance of XMLHttpRequest and use it to send the ZIP code to the server. Remember, this function will be invoked whenever the Zip input loses focus; that is, whenever the user enters the field and then leaves it, either with the mouse, the tab key, or some other mechanism. Here’s what it looks like so far:

1 <script type="text/JavaScript">
2 var xhr;
3 function getZipData(zipCode) {
4 xhr = new XMLHttpRequest();
5 xhr.open("GET", "/getCityStateFromZip.request?" + zipCode);
6 xhr.send(null);
7 }
8 </script>

On line 4, we create our XMLHttpRequest instance. On the next line, we configure it using the open( ) function; the first parameter indicates the HTTP method to use for the request, and the second indicates the URL we’ll be requesting. Finally, we invoke the send( ) function, which predictably enough sends the request.

Parsing the Response

Now that we’ve demonstrated how to send a request to the server, we need to add some code that will process the response that the server sends back. We’ll do that by creating a function processZipData( ):

1 function processZipData() {
2 var data = xhr.responseText;
3 var cityState = data.split(',');
4 document.getElementById("city").value = cityState[0];
5 document.getElementById("state").value = cityState[1];
6 }


The first few lines of this function are fairly intuitive; we retrieve the data sent back fromthe server—the city and state, formatted as “City,State”— and split the string into a two-element string array, so that we can access the city and state values separately. Lines 4 and 5 demonstrate why we gave id attributes to the City and State input elements earlier. Web browsers model every web page they display as an XML document (regardless of how ugly the page’s HTML markup is). In JavaScript code, we can access this XML document using the document variable. document has a handy getElementById( ) function that can return a reference to any XML element based on the id attribute. Once we have a reference to the element, we can manipulate it. In this case, we set the value attribute of the elements to the city and state values returned by the server.

Tying It All Together

We’ve created two JavaScript functions: getZipData( ), which sends a request to the server, and processZipData( ), which processes the response. However, we haven’t yet connected them. As our code currently stands, processZipData will never be invoked.


You might think that we should invoke processZipData( ) as we do on line 5 of the following example.

1 function getZipData(zipCode) {
2 xhr = new XMLHttpRequest();
3 xhr.open("GET", "/getCityStateFromZip.request?" + zipCode);
4 xhr.send(null);
5 processZipData();
6 }

Unfortunately, this just doesn’t work. The “A” in Ajax stands for asynchronous, and asynchronous behavior is exactly what we’re seeing here.

It turns out that when we invoke the send function on line 4, the invocation returns immediately and the XMLHttpRequest will make the request and receive the response on a separate thread. Thus, if we were to try to process the response from the server on the following line, we
couldn’t—we would not yet have received the response.
The solution is to register a callback handler—a function that will be callback handler
invoked when the XMLHttpRequest has received the response from the server. Line 3 in the following example demonstrates how to register processZipData as a callback handler:
1 function getZipData(zipCode) {
2 xhr = new XMLHttpRequest();
3 xhr.onreadystatechange=processZipData;
4 xhr.open("GET", "/getCityStateFromZip.request?" + zipCode);
5 xhr.send(null);
6 }


By simply passing the name of the function to the onreadystatechange( ) method, we are almost ready. Why is the method named onreadystatechange( ) and not, say, onresponsereceived( )? It turns out that XMLHttpRequest calls back into the function we registered multiple times as
it sends the request and receives the response, each time indicating that it has made progress. We’re only interested in parsing the data once the entire process has finished, so we need to check the current status of the XMLHttpRequest before we attempt to get the response data
in processZipData( ):
1 function processZipData() {
2 if (xhr.readyState == 4) {
3 var data = xhr.responseText;
4 var cityState = data.split(',');
5 document.getElementById("city").value = cityState[0];
6 document.getElementById("state").value = cityState[1];
7 }
8 }

XMLHttpRequest provides a readyState property that indicates its current status; a state of “4” indicates that the response has been received.


That’s it, we’re done. Let’s take a look at the entire web page source code to see how all these pieces fit together:
<html>
<head>
<title>Customer Data Screen</title>
<script type="text/javascript">var xhr;
function getZipData(zipCode) {
xhr = new XMLHttpRequest();
//<label id="code.xhr"/>
xhr.onreadystatechange=processZipData;xhr.open"GET","/getCityStateFromZip.request?" + zipCode);xhr.send(null);
}
function processZipData() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
var cityState = data.split(',');
document.getElementById("city").value = cityState[0];
document.getElementById("state").value = cityState[1];
}
}
</script>
</head>
<body>
<h1>Corporate System
</h1><h2>Enter Customer Data</h2><table><tr><th>Customer Name:</th><td><input type="text" name="name"/>
</td></tr><tr>
<th>Address:</th>
<td><input type="text" name="address"/>
</td></tr><tr><th>Zip:</th><td>
<input onblur="getZipData(this.value)"type="text" name="zip"/>
</td>
</tr>
<tr>
<th>City:
</th>
<td>
<input id="city" type="text" name="city"/>
</td>
</tr>
<tr>
<th>State:</th>
<td>
<input id="state" type="text" name="state"/>
</td>
</tr>
<tr>
<th>
</th>Report
<td><input type="Submit" value="Add Customer"/>
</td>
</tr>
</table>
</body>
</html>

Friday, January 4, 2008

Ajax Frameworks and Libraries - part1

The year 2006 has seen a rapid proliferation of Ajax and Javascript frameworks, from small cross-browser wrapper utilities to complete end-to-end client and server solutions. In this post, let's take a snapshot of some of the current range of offerings. These frameworks which will be described include the functionalities they had in that particular year and might have changed a lot as the time passed.

1. AccessKey Underlining Library
Open source
www.gerv.net/software/aul/
Adds accesskey underlining to pages without requiring tags in the source. Tag items with the accesskey attribute and javascript will create the appropriate underlining tags in the DOM.

2. ActiveWidgets
Commercial with free download
http://www.activewidgets.com/
Rich client JavaScript widgets; current flagship product is a rich grid widget.

3. Ajax JavaServer Faces Framework
Open Source (Apache)
http://smirnov.org.ru/en/ajax-jsf.html
The Ajax-JSF framework is designed to allow simple conversion of any existing JavaServer Faces application to Ajax functionality. Most of the existing components can be used as is or simply converted to Ajax support. Proposal to MyFaces project. Minimal differences from JSF specifications.
4. Ajax JSP Tag Library
Open Source
http://ajaxtags.sourceforge.net/
The Ajax JSP Tag Library is a set of JSP tags that simplify the use of Asynhronous Javascript and XML(Ajax) technology is JavaServer Pages. This tag library eases development by not forcing J2EE developers to write the necessary JavaScript to implement an Ajax-capable web form. Autocomplete retrieves a list of values that matches the string enteres in a text form field as the user types. Callout displays a callout or popout balloon, anchored to an HTML element with an onclick event. Select populates a second select field based on a selection within a drop-down field. Toggle switches a hidden form field between true and false and at the same time switches an image between 2 sources. Update Field updates one or more form field values based on the response to text entered in another field.

5. Ajax.NET
Michael Schwarz(2005)
Unspecified, free to use http://weblogs.asp.net/mschwarz/
Ajax.NET is a library enabling various kinds of access from JavaScript to server-side .NET. Can pass calls from JavaScript into .NET methods and back out to Java-Script callbacks. Can access session data from JavaScript. Caches results. No source code change needed on server-side; mark methods to expose with an attribute. Provides full class support for return values on client-side JavaScript, including DataTable, DataSet, DataView, Arrays and Collections.

6. AjaxAC
Open source(Apache2.0)
http://ajax.zervaas.com.au/
AjaxAC encapsulates the entire application in a single PHP class. All application code is self-contained in a single class (plus any additional JavaScript libraries). The calling PHP file/HTML page is very clean. You simply create the application class, then reference the application JavaScript and attach any required HTML elements to the application. No messy JavaScript code clogging up the calling HTML code; all events are dynamically attached. Easy to integrate with the templating engine, and hook into existing PHP classes or MySQL database for returning data from sub-requests. Extensible widget structure lets you easily create further JavaScript objects.

7. AjaxAspects
Free to use with source
http://ajaxaspects.blogspot.com/
AjaxAspects is an engine that uses JavaScript proxies to call server-side Web Service methods. Standard SOAP and WSDL is reused for the communication between client and server. Simple types and XML objects are supported as parameters and return values. Supports caching and quueing of actions.

8.AjaxCaller Michael Mahemoff(2005)
Open Source
http://ajaxify.com/run/testAjaxCaller
AjaxCaller is a basic thread-safe wrapper around XMLHttpRequest mainly for Ajax newcomers; still raw alpha and under development and is only packaged with the AjaxPatterns live search demos for now. Follows REST principles.

9.AjaxFaces
Open source(ASF)
http://myfaces.apache.org/
Apache's JavaServer Faces implementatio; currently experimenting with Ajax support.

10. BackBase
Commercial with community edition
http://www.backbase.com/
BackBase is a comprehensive browser-side framework with support for rich browser functionality as well as .NET and Java integration. BackBase provides Rich Internet Application(RIA) software that radically improves the usability and effectiveness of online applications and increases developer productivity. With BackBase you can build web applications with a richer and more responsive user interface. BackBase provides separation of presentation from logic through a custom XHTML namespace.

11. Behaviour
Ben Nolan(2005)
Open Source
www.ripcord.co.nz/behaviour/
Behaviour works by using CSS selectors to add JavaScript code to DOM elements. You can create a hash of CSS selectors and functions that take an element, and add JavaScript event handlers such as onclick. You then register these rules against a page and compare them against their matching DOM elements and the JavaScript code is added. The code is designed in a way that you can treat these rule files just like stylesheets so that all the page using them needs is an include. Behaviour's goal is to remove the heavy use of onclick attributes and script nodes from pages so they aren't messing up content. It works well and help make your JavaScript more reusable since it's more centralized.

12.Bindows
Commercial
http://www.bindows.net/
Bindows is a software development kit that generates highly interactive Internet applications with richness that rivals modern desktop applications using the strong combination of DHTML, JavaScript, CSS and XML. Bindows applications require no downloads and no installation on the user's side; only a browser is required(no Java, Flash or ActiveX is used). Bindows provides a range of widgets as well as native XML,SOAP and XML-RPC support.

13.BlueShoes
Commercial with free version
http://www.blueshoes.org/
Rich component suite, including a WYSIWYG text editor and spreadsheet widget.

14. CakePHP
Open source
http://cakephp.org/
A comprehensive port of Ruby on Rails to PHP, including top-notch support for Ajax.

15. CL-Ajax Richard Newman(2005)
Open Source
http://cliki.net/cl-ajax
CL-Ajax directs JavaScript calls directly into server-side Lisp functions. Generates JavaScript stub with arguments. Can call back to JavaScript functions or DOM objects. May be integrated into SAJAX.

16. ComfortASP.NET
Pre-release commercial with free download
www.daniel-zeiss.de/ComfortASP/
ComfortASP.NET is an approach that lets developers rely on pure ASP.NET programming while offering Ajax-like features. ComfortASP.NET uses Ajax (DHTML, Javascript, XMLHTTP) to implement these features, but the web developer only implements pure server-side ASP.NET.

17. Coolest DHTML Calendar
Open Source with commercial support
www.dynarch.com/projects/calendar
Configurable Javascript calendar widget; can be wired up to form fields as a drop-down or pop-up and styled using CSS.

18. CPAINT (Cross Platform Asynchronous Interface Toolkit)
Open Source(GPL and LGPL)
http://cpaint.sourceforge.net/
CPAINT is a true Ajax implementation and JSRS (Javascript Remote Scripting) implementation that supports both PHP and ASP/VBScript. CPAINT provides you the code required to implement Ajax and JSRS on the back-end, while the returned data is manipulated, formatted and displayed on the front-end in JavaScript. This allows you to build web applications that can provide near real-time feedback to the user.

19. Dojo Alex Russell (2004)
Open Source
http://dojotoolkit.org/
Dojo provides several libraries for use with Ajax, including widgets, an event model, and messaging using XMLHttpRequest and other techniques. Aims to support JavaScript in a range of settings, including SVG and Netscape's Java based Rhino engine, as well as in the web browser.

20. DWR (Direct Web Remoting)
Open source
www.getahead.ltd.uk/dwr
Direct Web Remoting is a framework for calling Java methods directly from Java Script code. Like SAJAX, it can pass calls from JavaScript into Java methods and back out to Javascript callbacks. It can be used with any web framework - such as Struts or Tapestry - following a Spring-like KISS/POJO/orthogonality philosophy. Direct Web Remoting is due to be incorporated into the next release of the Open Symphony WebWorks framework.

21. Echo 2
Open source (MPL or GPL)
www.nextapp.com/products/echo2
Echo 2 allows you to code Ajax apps in pure Java. Automatically generates HTML and Javascript, and co-ordinates messages between the browser and the server. Offers messaging in XML. The developer can handwrite custom Javascript components if desired.

22. f(m)
Open Source
http://fm.dept-z.com/
The f(m) project is an ECMAScript Base Class Library, based on the .NET Framework, that was written to serve as the foundation for a new breed of browser-based web applications.

Ajax Frameworks and Libraries- Part2

23. FCKEditor
Open source
www.fckeditor.net
Rich WYSIWYG editor widget; can be swapped in for an HTML text area in one line of javascript code, allowing easy integration with existing web applications, CMS, wikis and so forth. Very similar functionality to TinyMCE.

24. Flash JavaScript Integration Kit
Open source
www.osflash.org/doku.php?id=flashjs
The Flash JavaScript Integration Kit allows for the integration of JavaScript and Flash content. Enables JavaScript to invoke ActionScript functions and vice versa. All major data types can be passed between the two environments.

25. Google AjaxSLT
Open source license (BSD)
http://goog-ajaxslt.sourceforge.net
AjaxSLT is offered by the innovative search solutions company that refers to itself as "Google". Google AjaxSLT is a javascript framework for performing XSLT transformations as well as XPath queries. Builds on Google Map work.

26. Guise
Commercial with free downloads
www.javaguise.com
Java-based server side component model(similar in some ways to JSF, but simpler). Currently integrates Ajax functionality for greater responsiveness.

27. HTMLHttpRequest
Angus Turnbull (2005)
Open source(LGPL)
www.twinhelix.com/JavaScript/htmlhttprequest/
Simple remote scripting wrapper. Uses XMLHttpRequest and IFrames as well for improved compatibility.

28. Interactive Website Framework
Open source
http://sourceforge.net/projects/iwf/
Interactive Website Framework is a project whose aim is to support the various aspects of Ajax infrastructure in the browser. Describes itself as a framework for creating highly interactive websites using Javascript, CSS, XML and HTML. Includes a custom XML parser for highly readable Javascript. Contains essentially all the plumbing for making Ajax-based websites, as well as other common scripts. Provides a thread safe XMLHttpRequest implementation and a wrapper around the DOM making for more readable code.

29. Jackbe
Commercial
www.jackbe.com/solutions/development.html
Ajax rich client widget suite; can be plugged into any middleware technology such as ASP, Java, .NET or PHP.

30. JPSpan
Open source
http://jpspan.sourceforge.net/wiki/doku.php
JPSpan passes JavaScript calls directly to PHP functions. Heavily unit-tested.

31. jsolait
Open source (LGPL)
http://jsolait.net
Set of open source Javascript libraries, including cryptography, serialization and deserialization, XML-RPC and JSON-RPC.

32. JSON
Open source; most implementations are LGPL
http://json-rpc.org/
JSON is a "fat free XML alternative" and JSON-RPC is a remote procedure prototcol, akin to XML-RPC, with strong support for JavaScript clients. Implementations exist for several server-side languages and platforms, including Java, Python, Ruby and Perl.

33. JSRS (JavaScript Remote Scripting)
Brent Ashley (2000)
www.ashleyit.com/rs/jsrs/test.htm
JSRS routes calls directly from JavaScript into your server-side language and back out again. Known browsers: IE 4+, Netscape 4.x, Netscape 6.x, Mozilla, Opera 7 and Galeon. Server-side support: ASP, ColdFusion, PerlCGI, PHP, Python and JSP(servlet).

34. LibXMLHttpRequest
Stephen W.Coate
Source available, protected by copyright
www.whitefrost.com/servlet/connector?file=reference/2003/06/17/libXml-Request.html
LibXMLHttpRequest is a thin wrapper around XMLHttpRequest.

35. Mochikit
Open source
www.mochikit.com/
Mochikit is a set of libraries whose highlights include logging, visual effects, asynchronous task management, string and date/time formatting and a "painless" DOM manipulation API that makes heavy use of JavaScript's built-in Array objects and JSON-like notation to represent the DOM.

36. netWindows
Open source
www.netwindows.org
Complete DHTML desktop/windowing environment inside the browser. Code is purely standards-based, with no browser hacks. Contains a "signals and slots" messaging implementation, modeled after Trolltech's Qt widgets and the Small-talk language; also available as a standalone library.

37. Oddpost
Commercial
www.oddpost.com
JavaScript widget suite; includes fully functional rich e-mail client. Now part of Yahoo!.

38. OpenRico
Bill Scott, Darren James (2005)
Open source
http://openrico.org
A multipurpose framework with support for Ajax. Covers user interface issues such as animations, separation of content from logic through behaviours, drag and drop, and some prebuilt widgets, notably a data grid. Sponsored by Sabre Airline Solutions; has seen real world use. Built on top of Prototype.

39. Pragmatic Objects
Open source
http://pragmaticobjects.com/products.html
Pragmatic Objects WebControls is a set of JSP tag libraries designed as reusable controls or components to enrich Java-based web applications. As opposed to rich but fat web applications, a thin client web application, at the end of the day, consists of nothing but a series of HTML pages, containing JavaScript and CSS codes that are rendered by the browsers. Current offerings consist of an "outlook bar", a tree widget and a control panel.

40. Prototype
Sam Stephenson
Open source
http://prototype.conio.net
Prototype is a Javascript framework designed for RIA development. It includes a solid Ajax library and a toolkit to simplify use. Prototype is the JavaScript engine for Ruby on Rails, Rico, and Scriptaculous, among others. Prototype's JavaScript code is generated from Ruby, but the generated Javascript may be deployed in non-Ruby environments.

41. Qooxdoo
Open source (LGPL)
http://qooxdoo.sourceforge.net
This is an Ajax user interface library with a large range of prebuilt components and a well-thought-out design. Includes widgets, layout managers, and portable PNG transparency. Also provides development support such as timers for profiling and debugger support.

42. RSLite
Brent Ashley
www.ashleyit.com/rs/main.htm
A simple component released as part of Brent Ashley's more comprehensive Remote Scripting work.

43. Ruby on Rails
David Heinemeier Hansson (2004)
Open source
www.rubyonrails.org
Ruby on Rails is a general framework with strong Ajax support. Rails was still in its early days when the Ajax hype began, so Ajax may become increasingly core to the Rails framework. Generated most if not all of the JavaScript for widgets and animation in the browser. Support for calling server-side. Scheduling support. Current darling of the fashionable web development crowd, Ruby on Rails eschews the complex, over-designed, cover-all-bases strategy in favour of a straightforward, getting-the-job-done approach, with the help of a good deal of code generation. Has won over many Java developers for that reason.

44. Sack
Open source (modified MIT/X11)
http://twilightuniverse.com/2005/05/sack-of-ajax
Sack is a thin wrapper around XMLHttpRequest. The caller can specify a callback function or a callback DOM object. With a callback DOM, the response text is pushed directly into the DOM.

45. SAJAX
Open source
www.modernmethod.com/sajax
SAJAX routes calls directly from JavaScript into your server-side language and back out again. So, for example, calling a JavaScript method x_calculateBudget() will go to the server and call a Java calculateBudget() method, then return the value in Javascript to x_calculateBudget_cb(). Facilities mapping from a JavaScript stub function to a back-end operation. Capable of stubbing calls to numerous server-side platforms: ASP, ColdFusion, Io, Lua, Perl, PHP, Python and Ruby.

46. Sarissa
Open source
http://sarissa.sf.net
Sarissa is a JavaScript API that encapsulates XML functionality in browser-independent calls. Supports a variety of XML technologies, including XPath queries, XSLT and serialization of JavaScript objects to XML, in a browser-neutral way.

47. Scriptaculous
Thomas Fuchs
Open source
http://script.aculo.us
Scriptaculous is a well-documented visual effects library built in Javascript on top of Prototype. It includes demos, sample applications, and a drag-drop library.

48. SWATO
Open source
http://swato.dev.java.net
SWATO (Shift Web Application TO...) is a set of reusable and well-integrated Java/Javascript libraries that give you an easier way to shift the interaction of your web apps through the Ajax way. The server-side Java library can be easily deployed in all Servlet 2.3+ compatible containers. The client-side JavaScript library can be worked in various browsers, as long as XMLHttpRequest is supported. SWATO uses JSON to marshal the data of your POJOs on the server side, so that you can access the remote data in any Javascript environment(HTML, XUL, SVG) easily by either hard-coding or by integrating with mature JavaScript libraries. Comes with several reusable components(Auto-complete Textbox, Live Form, Live List, etc.) that help you develop your web apps rapidly.

49. Tibet
Commercial
www.technicalpursuit.com
Tibet aims to provide a highly portable and comprehensive Javascript API, so that a great amount of client-side code is possible. Pitches itself as "Enterprise Ajax" supports web service standards such as SOAP and XML-RPC, with pre-built support for some popular web services such as Google, Amazon, and Jabber instant messaging. Includes an IDE written in JavaScript using the Tibet toolkit.

50. Tiny MCE
Open source with commercial backing and some proprietary plug-ins
http://tinymce.moxiecode.com/
Rich WYSIWYG editor widget; can be swapped in for an HTML textarea in one line of JavaScript code, allowing easy integration with existing web-applications, CMS, wikis, etc. Very similar functionality to FCKEditor.

51. TrimPath Templates
Open source
http://trimpath.com/project/wiki/JavaScriptTemplates
JavaScript template engine for splicing together data and presentation on the browser.

52. Walter Zorn's DHTML Libraries
Open source
http://www.walterzorn.com/index.htm
DHTML libraries for drag and drop support, and for vector graphics drawing of lines and curves by using DIV elements as pixels.

53. WebORB for .NET
Commercial with free edition
www.themidnightcoders.com/weborb/aboutWeborb.htm
WebORB for .NET is a platform for developing Ajax and Flash-based rich client application and connecting them with .NET objects and XML web services.

54. WebORB for Java
Commercial with community/free edition
www.themidnightcoders.com/weborb/aboutWeborb.htm
WebORB for java is a platform for developing Ajax and Flash-based rich client application and connecting them with Java objects and XML web services. Includes a client-side library called Rich Client System. (www.themidnightcoders.com/rcs/index.htm). The Rich Client System provides a simple one-line API to bind to and invoke any method on any Java object, XML web service or Enterprise JavaBean. Provides a special API for handling database query results; the server code can return DataSets or DataTables, and the client presents it as a special RecordSet JavaScript object. The object provides a way to retrieve column names as well as row data.

55. x
Mike Foster
open source
www.cross-browser.com
Veteran DHTML library, providing cross-browser support for animation, styling, events and other common functionality.

56. XAJAX
J.Max Wilson
Open source
http://xajax.sf.net
XAJAX passes JavaScript calls directly to PHP functions. Use a JavaScript stub to call a PHP script.

57. x-Desktop
Open source
www.x-desktop.org/
This project comprises a library for developing thin client application front-ends using a browser. It helps developers to create GUI application interfaces for Internet, intranet and extranet applications. x-Desktop features include the fact that it is browser bsed and that no plug-ins are required. It supports all operating systems that provide a DOM 2/JavaScript capable browser; offers a simple well-documented object interface; and provides a customizable desktop and window skins.

58. XHConn
Brad Fults
http://xkr.us/code/JavaScript/XHConn
XHConn is a thin wrapper around XMLHttpRequest.

Thursday, January 3, 2008

Introduction to Dojo Toolkit

This post is geared towards people with some javascript knowledge, that might have used another ajax/js framework before, but now have a really pressing need to use some of the features found in dojo framework.So, what is it really?

Dojo is quite a lot of things. It has a staggering amount of widgets, to begin with; Dialogs, Panes, Menus, WYSIWYG editors, Buttons, Color pickers, Clocks, Layout Managers and a host of other things- just in the widgets department. Then there's the very handy encryption package, handy for hashing things coming to and from the server-side, the Drag-n-Drop package which works with nearly any element on the page, the essential Collections API with Java-like iterators and what not, and of course the powerful proper Ajax functionality with several bells and whistles of its own.
Apart from the sheer amount of functionality available in dojo, there are a few architectural differences compared to most other frameworks; Dojo uses namespaces. This means that dojo always includes the package names in an object reference. If I want use the very nice for-each loop function, for instance, I have to refer to is like this; "dojo.lang.forEach(listOfThings, myFunc);” instead of just "forEach(listOfThings, myFunc);".It seems to be a lot of trouble and waste a lot of space, but in reality it's not a big change and it increases readability when debugging or refactoring things later. Another example is that when you want to refer to a DOM element the "dojo way", you write "dojo.byId(el.id);" instead of prototypes inarguably more compact "$(el.id);" Another big change in philosophy between dojo and prototype is that prototype has a long and glorious history of changing basic javascript objects, such as adding useful new functions to the string object.This has resulted in collisions or erratic behavior when using other javascript libraries which want to change or assume a certain functionality of the very same function names. By using namespaces, dojo ensures that no collisions occur between itself and any other libraries on the same page.Getting the right stuff and copying the right files to your server You might think that using a javascript-based framework should be dead simple. In many cases it is, but due to de facto standards set up by many smaller frameworks (or libraries), some design choices in dojo requires reading some of the fine print. The most important thing to remember is that dojo is more that just the file dojo.js. It is not uncommon for people starting to use dojo to assume that the src/ directory really isn't needed, and probably is shipped only as a kind of open source service to the developer. However, when you download and unzip the "standard" dojo package (dojo 0.4.2-ajax), the dojo.js file is only the starting point, the kernel so to speak, of dojo. All real functionality exists - and exists only - in files under the src/ directory. Also, most widgets have a lot of template html files and images that they have to get at, so the short dance version of this point is; Copy everything.

Check the test to see how things are done The biggest problem the dojo community faces (IMHO) is the lack of a thorough API documentation and walk-through examples. True, there's a very useful (at least to the intermediate-level dojo hacker) API tool, and there are several good sites which give fairly up-to-date walk-throughs and examples in specific areas. But the really good bits can be found on the test directory which also ships with the standard package. If you go to http://download.dojotoolkit.org/release-0.4.2/dojo-0.4.2p1-widget you'll see two interesting directories; demo and tests. The reason I refer to the live URL at the dojo download site is that you might want to poke around at other (upcoming) versions. The demo directory contains a fair number of demos, which are neatly organized in the following sections; Demo Applications (Mail client, Text editor), Effects (Fades, Wipes, Slides, et.c.), Drag and Drop, Storage, RPC, Layout Widgets, Form Widgets and General Widgets (Buttons, Menus, Fisheye menus, Tooltips, et.c.). This is a good place to let your jaw drop a bit and get some inspiration. But the really good stuff is found under the tests directory. Here you will find unit tests for almost all widgets, layout containers, graphics, and lots of other things you'll find truly useful. The reason the tests are more useful is that they are short, focused and sometimes even (drumrolll, please) commented! My recommendation is to check out tests/widget for test_ModalFloatingPane, test_Dialog and test_Menu2_Node for some basic examples on how to use dojo widgets. Although dojo is an Ajax framework, much of the truly sterling functionality it offers has little if anything to do with client-sever communication - as you will find out.Before you do the fancy stuff you're surely shaking with barely controlled desire to do, it's a good idea to get a minimal "template-page" up and running. Of course, you could just grab one of the tests files and change things about, but how fun would that be? Here is a minimal html-page to start with, happily snarfed from one of the Dialog tests and shortened a bit;

<html>
<head>
<title>My first Dojo page</title>
<script type="text/javascript" src="dojo.js"></script>
<script type="text/javascript">
dojo.require("dojo.widget.*");
</script>
<script>
var dlg;
function getResults(evt)
{
var name = dojo.byId("inputname").value;
dojo.byId("namediv").innerHTML = "<b>"+name+"</b>";
}
function init(e)
{
dlg = dojo.widget.byId("DialogContent");
dojo.event.connect("hider", "onclick", "getResults");
}
dojo.addOnLoad(init);
</script>
</head>
<body>
<a href="javascript:dlg.show()">Show Dialog</a> <br><br>Name:<div id="namediv">None</div>
<div dojoType="dialog" id="DialogContent" bgColor="white" bgOpacity="0.5" toggle="fade" toggleDuration="250" closeNode="hider">
<h3>First Dialog</h3>
<form onsubmit="return false;">
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="inputname"></td>
</tr>
<tr>
<td>Description:</td>
<td><input type="text"></td>
</tr>
<tr>
<td>Location:</td>
<td><input type="file"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" id="hider" value="OK"></td>
</tr>
</table>
</form>
</div>
</body>
</html>

The first thing that happens here is that we load the file dojo.js, where among other things the dojo.require function is defined. Then we call that require function for the things we really need in our page. We could have just added a lot of script statements to get pretty much the same effect, but what's with the require loader is that we can use wildcards to load a whole package at a time, for instance dojo.widget.*. This OK when doing happy testing, but in production it's a good idea to only load what you need.
Note also that the package structure of dojo is the same as the file structure, and actually derives from it. This means that if you create subdirectories for your own dojo-derived widgets or whatever, you can use the loader for them as well.Then comes a script section where we define the variables and setup function to use in the page, which are page-specific. We could have taken these out and put them in a separate file, which we then could load use the standard script tag. As long as it's only a dozen lines or so, I actually prefer to have them in the html file, if the logic is tightly coupled (as in this case) to the nearby elements.There are two function, one obvious callback function, which reads the value of an input field, and copies that the value of another element on the page. The other function is a setup function which calls the first function when the form is closed. It does so using dojos own dojo.event.connect function, which is very powerful and requires an article in its own right, but for our purposes here it suffices to say that it hides any browser quirks, to make events simpler to work with.The rest of the page consists of two parts; a link which shows the dialog form, and the dialog form itself. Note the lazy javascript in the href of the anchor tag, which uses the variable defined earlier to show the dialog.The second part of the page shows the standard dojo way of declaring widgets, by adding a 'dojotype' tag inside the element, which defines the type of widget to be created for the element. Note also the tag 'closeNode', which defines which node controls calls to the hide() function of the dialog.When the link is clicked on the page, the dialog is shown, and when the "OK" button is clicked the dialog is hidden and the getResults() function is called.

Wednesday, January 2, 2008

EVOLVING PORTAL

More and more companies have been adopting a portal-based intranet. Portals give users an easy gateway for obtaining large quantities of information on one page. This eliminates the need for the user to go to multiple locations to get the information they need. Online portals such as Yahoo! allows us to obtain news, weather, sports scores, mail, games and so much more on just one page. Another portal is Amazon’s A9.com search portal, which lets us do searches on multiple areas without going to separate pages. We can search for web pages, books, images and much more on one page. A9.com utilizes Ajax to display the information on the screen. This allows for a great user experience since the user does not have to sit and wait for page re-rendering when new search results are displayed.

THE EVOLVING PORTAL

Over the time, portals have evolved from simple sites that let us check our mail and do a search to elaborate setups that allow us to obtain a large amount of information in little effort. By comparison, in the past we had to check one site for news, another for comics, and another for a search and so on. Either we had tons of bookmarks for the sites that we checked daily or we just mentioned our routine of what addresses to type into the browser.
THE CLASSIC PORTAL
We are all accustomed to classic portals – we have been using them for years – and a lot of company intranets are using them to improve company performance by having everything in one place. The classic portal is one that allows a user to log into the system and have the content personalized to her tastes. For example, a company portal can have one setup for a salesperson and another setup for a computer programmer. Both of these employees may need to have a window to the company calendar, but they both may not need to see the sales figures or the bug report for the applications. By limiting what they can see, we increase company security and improve the employees performance since they do not have to search for information all over the company intranet.
Another example of a classic portal is Yahoo! When we log into Yahoo!, we can check mail, change the weather to fit our current location, change the look and so much more. As shown in the figure, Yahoo!’s portal is customized to the needs of the user.

Before incorporating Ajax, Yahoo! accomplished this by sending us to maintenance screens to alter the information. One example of the maintenance page allows us to select the city that we live in so that the weather forecast is for our area. Later they have enhanced the user experience even more by incorporating Ajax into the portal in the same way that Amazon did with the A9.com portal.


THE RICH USER INTERFACE PORTAL

With an Ajax portal, the rich user interface is more dynamic than a classic portal while positively impacting the user’s experience. We can add new content and change the way the content is displayed in a seamless manner. A great example of this seamless interaction is in Amazon’s A9.com search portal. Let’s look at how that works. In the following figure, a search has been performed for Eric Pascarello with only the web checkbox selected.



Now let’s narrow the search results. We know that we are looking for a book that Pascarello has written, so we click the Book checkbox. The Book Results page is inserted into the right-hand side of the page. The search results for Eric Pascarello’s books are displayed without posting the entire page back to the server to obtain them.
Another example of using Ajax to enhance the portal experience is in the configuration of the portal. Ajax allows the user interface to become part of the configuration-management tools by having the user click on objects in the window instead of going to another web-page to configure the setup. The user can dynamically resize and position the elements on the screen, thus customizing his portal to fit his needs exactly.

Tuesday, January 1, 2008

ALTERNATIVE TO AJAX

By now, nearly everyone who works in web development has heard of the term Ajax, which is simply a term to describe client-server communication achieved without reloading the current page. Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques aren't limited to just XMLHttpRequest. There are several other methods to achieve what AJAX can give to the end-user.
Dynamic Script Loading
The first alternate Ajax technique is dynamic script loading. The concept is simple: create a new <script/> element and assign a JavaScript file to its src attribute to load JavaScript that isn't initially written into the page. The beginnings of this technique could be seen way back when Internet Explorer 4.0 and Netscape Navigator 4.0 ruled the web browser market. At that time, developers learned that they could use the document.write() method to write out a <script/> tag. The caveat was that this had to be done before the page was completely loaded. With the advent of the DOM, the concept could be taken to a completely new level.
The Technique
The basic technique behind dynamic script loading is easy, all you need to do is create a <script/> element using the DOM createElement() method and add it to the page:
var oScript = document.createElement("script");oScript.src = "/path/to/my.js";document.body.appendChild(oScript);
Downloading doesn't begin until the new <script/> element is actually added to the page, so it's important not to forget this step. (This is the opposite of dynamically creating an <img/> element, which automatically begins downloading once the src attribute is assigned.)
Once the download is complete, the browser interprets the JavaScript code contained within. Now the problem becomes a timing issue: how do you know when the code has finished being loaded and interpreted? Unlike the <img/> element, the <script/> element doesn't have an onload event handler, so you can't rely on the browser to tell you when the script is complete. Instead, you'll need to have a callback function that is the executed at the very end of the source file.
Example 1
Here's a simple example to illustrate dynamic script loading. The page in this example contains a single button which, when clicked, loads a string ("Hello world!") from an external JavaScript file. This string is passed to a callback function (named callback()), which displays it in an alert. The HTML for this page is as follows:

<html>
<head>
<title>Example 2</title>
<script type="text/javascript">//<![CDATA[
function makeRequest(sUrl, oParams) {
for (sName in oParams) {
if (sUrl.indexOf("?") > -1) {
sUrl += "&";
} else {
sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);
}
var oScript = document.createElement("script");
oScript.src = sUrl;
document.body.appendChild(oScript);
}
function messageFromServer(sText) {
alert("Loaded from file: " + sText);
}
function getInfo() {
var oParams = {
"name": document.getElementById("txtInput").value, "callback": "messageFromServer"
};
makeRequest("example2js.php", oParams);
}
//]]>
</script>
</head>
<body>
<input type="text" id="txtInput" value="Nicholas" />
<input type="button" value="Get Info" onclick="getInfo()" />
</body>
</html>

The JavaScript file example1.js contains a single line:
callback("Hello world!");
When the button is clicked, the makeRequest() function is called, initiating the dynamic script loading. Since the newly loaded script is in context of the page, it can access and call the callback() function, which can do use the returned value as it pleases. This example works in any DOM-compliant browsers (Internet Explorer 5.0+, Safari, Firefox, and Opera 7.0.

More Complex Communication
Sometimes you'll want to load a static JavaScript file from the server, as in the previous example, but sometimes you'll want to return data based on some sort of information. This introduces a level of complexity to dynamic script loading beyond the previous example.
First, you need a way to pass data to the server. This can be accomplished by attaching query string arguments to the JavaScript file URL. Of course, JavaScript files can't access query string information about themselves, so you'll need to use some sort of server-side logic to handle the request and output the correct JavaScript. Here's a function to help with the process:
function makeRequest(sUrl, oParams)
{
for (sName in oParams) {
if (sUrl.indexOf("?") > -1) {
sUrl += "&"; } else { sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]); }
var oScript = document.createElement("script"); oScript.src = sUrl; document.body.appendChild(oScript);
}
This function expects to be passed a URL for a JavaScript file and an object containing query string arguments. The query string is constructed inside of the function by iterating over the properties of this object. Then, the familiar dynamic script loading technique is used. This function can be called as follows:

var oParams = { "param1": "value1", "param2": "value2"};
makeRequest("/path/to/myjs.php", oParams)

Next, you need a way to assign the callback function to be used. It's quite possible that you'll want to access the same information on different pages and in different ways. Forcing each page to have a callback function named "callback" isn't very good architectural design. Instead, it would be better to tell the JavaScript file the name of the callback function to use so that it can be dynamically inserted. The name of the function can be passed as another parameter for the query string:

var oParams = { "param1": "value1", "param2": "value2", "callback": "myCallbackFunc"};
makeRequest("/path/to/myjs.php", oParams);

The file creating the JavaScript then has to take the name of the callback function and output it into the code, as below:

var sMessage = "Hello world!";
(sMessage);

The first part of this file sets the content type to text/javascript so that the browser recognizes it as JavaScript (though many browsers don't check the content type of files loaded using <script/>) Next, a JavaScript variable called sMessage is defined as a string, "Hello world!". The last line outputs the name of the callback function that was passed through the query string, followed by parentheses enclosing sMessage, effectively making it a function call. If all works as planned, the last line becomes:
myCallbackFunc(sMessage);

Example 2
This example builds upon the previous one, but this time, you're going to send some additional information to the server and tell it which callback function to call. First, take a look at the PHP file that will be outputting the JavaScript:


var sMessage = "Hello, ";var sName = "
";
(sMessage + sName);

The JavaScript that will be output defines two variables, sMessage and sName; the former is filled with "Hello, ", the latter is assigned the value of the name parameter in the query string. Then, the name of the callback function is out, passing in the concatenation of sMessage and sName (combining server-side data with data passed from the client).
On the client side, the web page contains a textbox and a button:

html>
<head>
<title>Example 2</title>
<script type="text/javascript">//<![CDATA[
function makeRequest(sUrl, oParams) {
for (sName in oParams) {
if (sUrl.indexOf("?") > -1) {
sUrl += "&";
} else {
sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);
}
var oScript = document.createElement("script");
oScript.src = sUrl;
document.body.appendChild(oScript);
}
function messageFromServer(sText) {
alert("Loaded from file: " + sText);
}
function getInfo() {
var oParams = {
"name": document.getElementById("txtInput").value, "callback": "messageFromServer"
};
makeRequest("example2js.php", oParams);
} //]]>
</script>
</head>
<body>
<input type="text" id="txtInput" value="Nicholas" />
<input type="button" value="Get Info" onclick="getInfo()" />
</body>
</html>

When the button is clicked, the getInfo() method is called, which loads an object with a name parameter (taken from the textbox) and a callback parameter. Then, the makeRequest() function is called, passing in these values. After the script has been loaded, the messageFromServer() function will be called, popping up a message displaying what was received from the server

Drawbacks
Though dynamic script loading is a quick and easy way to establish client-server communication, it does have some drawbacks. For one, there is no feedback once the communication is initiated. If, for example, the file you are accessing doesn't exist, there is no way for you to receive a 404 error from the server. Your site or application may sit, waiting, because the callback function was never called.
Also, you can't send a POST request using this technique, only a GET, which limits the amount of data that you can send. This could also be a security issue: make sure you don't send confidential information such as passwords using dynamic script loading, as this information can easily be picked up from the query string.

LinkDirectory.com is a brand NEW 100% SEO friendly and an Entirely human edited link directory.
DaniWeb IT Discussion Community
Blog Search, Blog Directory
Directory of Computers/Tech Blogs