Search the Web:

Google

Monday, December 31, 2007

HISTORY OF AJAX

Many a year ago, Jeff Rouyer won the Netscape DHTML competition with his flying dude interface and put DHTML on the map. The winning entry, apart from being 3D in design which up until that point had not been seen on the Web, also had something that was quite uncharacteristic of Web pages.
Most of what you see today on the web in terms of DHTML Widgets can be attributed to a small number of people with Jeff leading the way. Granted there has been a progression over the years, but things like scrollers, tooltips, drag and drop, event handling, dynamic clipping etc were pioneered by Jeff many years before they became popular. For example, the sliding doors technique used in CSS today was used around ten years ago with JavaScript by Jeff. In short the guy is the grand daddy of DHTML and everyone else pales in comparison. I kid you not!

One of the unusual features of Jeff’s Award winning site was than rather than have a user traverse across multiple Web pages which consumes resources by opening separate window instances, Jeff was loading content dynamically into an existing interface. In other words all the content was being loaded into an existing element and all other elements were not being changed or swapped. We are talking pre Internet Explorer 4 days here.

Internet Explorer 4 was released a little later to challenge Netscape's dominance on the web, but it did not have a similar method where content could be loaded directly into a layer element by using layer.load();

As the popularity of Internet Explorer 4 gained it became increasingly important to Jeff to maintain cross browser compatibility and initially created a series of document.write() in an external file to allow content to be imported into a pre-existing html file. Obviously this was resource intensive and he went on to improve this method for Internet Explorer 4 by created a little Java Applet to allow Internet Explorer 4 to pass external content into an existing element.

Not long after that, he thought of the idea of using an IFrame technique where content would be loaded into a hidden IFrame and then sucked back out and into a div element. This was the genesis of what today is known as Remote IFrame Scripting. Remember we are talking close to a decade ago which is a good indicator of how far ahead of the curve Jeff was at the time.

Enter Ajax

Recently Garret Smith of Adaptive Path made a good case for using Asynchronous JavaScript and XML and coined the acronym "AJAX" to represent the notion of Remote IFrame Scripting. It is similar to the Remote IFrame technique in that things are handled on the client side, but as we shall see differs in significant ways.

Ajax is more a natural progression from an existing set of techniques as opposed to being something completely brand new. Yet within that progression, things are markedly different than in previous years in a couple of key areas:


· It provides a mechanism to mix and match xml with xhtml.
· It significantly reduces having to continually fetch things from a server (remote IFrame scripting is reasonably comparable here).
· It overcomes some speed bottlenecks that traditional Web development has fallen prey too. In most instances an Ajax based site will load quicker than a comparable traditional Web site.
· When done well, it significantly reduces initial load times.

Before proceeding, it should be noted that Ajax isn't a panacea. It has some problems that it needs to overcome as it continues to mature. But it is a promising field to be involved within and as the years roll on, it probably will greatly affect the way we think about building Web pages and Web applications.

It also needs to be clear that Ajax isn't a technology as such but rather is a technique that combines well with other technologies and techniques. For example, xml, dhtml, css, xhtml. In fact, Ajax really is DHTML with the xmlhttprequest object thrown in. It is amazing to think how one object can change the whole playing field.

As things currently stand in the Ajax field, we almost have two extremes going on. At one end of the continuum we have developers building all sorts of complicated JavaScript tags that in most instances are unnecessary and are overkill. At the other end of the scale we have these little examples floating around the Web that demonstrate how to load xml into a document or do some Ajax form processing.

What is Ajax?

Ajax itself is a technique, but to use the technique effectively one must become familiar with the philosophy behind the technique. In other words, it is not just the use of the technique that is important, but rather developing a different mindset and approach to Web development that is central.

To date, I have mentioned the term Ajax a number of times but have not described the central object that makes Ajax, Ajax. At the heart of Ajax are the xmlhttprequest object and its Microsoft's activeX equivalent. It is this object that allows data to be transferred asynchronously. In case you are not clear what asynchronous means, it is the ability to handle processes independently from other processes. Synchronous which is the opposite of asynchronous, then means that processes are dependent upon other processes. To illustrate let us use a classical Web page scenario.

Assume we have page A and on this page we have a number of elements, including a couple of script and style tags. With synchronous data transfer the script tag needs to be parsed before the next element is parsed. In this way then the next element to be parsed by the browser is dependent upon the script tag being parsed first. Effectively we are creating a bottleneck of one connection between Web page and browser. Style tags and link elements in the head section of the document create the same bottleneck effect. They have to be parsed one at a time before other page elements can download.

Once they have been parsed then the elements in the body section can use concurrent connections to help speed up the download process. For example, most servers handle between 2 to 4 concurrent connections between web page and browser.

Consequently, this means that 2 to 4 images or other page elements can load concurrently. Yet before that process starts what is between the head tags have to be parsed first, which can considerably delay the loading of web pages. Most particularly if you are using multiple CSS and JavaScript tags. Nearly every Web page and blog on the internet uses this method. It isn't hard to see why this may be a problem in terms of increasing page load speeds.

Asynchronously loading methods differ from this scenario because the loading processes are handled independently of each other and to a significant degree overcomes the bottle of traditional Web page design. As will be demonstrated later, the whole gist of this technique is to use minimal JavaScript initially and then push all the head related tags, including the rest of the JavaScript, CSS etc tags through an xmlhttprequest object. This method uses multiple connections rather than the single one that most traditional Web pages use and consequently speeds things up considerably.

AJAX toolkits as on Dec 2007


What is interesting about the Ajax market is that it’s more diversified in 2007 than it was in 2005 - the number of toolkits keep growing and jostling position in terms of usage. Right now there are 241 Ajax toolkits and related libraries listed in the survey. There were about three dozen in 2005 and 170 in 2006. The number of options is growing.
Prototype and Script.aculo.us are the only toolkits to maintain a lead over the past three years. However, over all there are no clear winners or losers as even the strongest incumbents (i.e., Prototype and Script.aculo.us) are starting too loose ground. Some frameworks initially popular have faded nearly completely out of the market (i.e., xajax and Rico ) while others have sprung out of nowhere to become leading tookits (i.e., jQuery and Ext JS).
What is astonishing is the nearly complete lack of commercial Ajax frameworks. Backbase has had a lot of success making a comeback after loosing some market share in 2006, but other commercial Ajax frameworks have not been so lucky.


AJAX FRAMEWORKS

The best technology to build dynamic web pages is Ajax. JavaScript code embedded into the HTML page is used to send requests to the server. At the server side, some processing is required to handle them, find the info or store the data. To do that, we need for a specialized framework. The framework has always a JavaScript part, and sometimes a server side part in another scripting language. A lot of them exist in various programming languages, in all environments around, but we retain here only the most widely used.

Summary
Why a framework?
Features of an Ajax framework
JavaScript libraries
PHP frameworks
Java frameworks
.NET frameworks
ColdFusion frameworks
Ajax and XUL
Beyond Ajax

Why a framework?
Actually, this framework is the Ajax engine described by J. J. Garrett and intended to suppress waiting for the user when accessing the server. The framework provides classical, cross-browser functions to use the XMLHttpRequest object. But a framework may go beyond that, and allow you to build "rich web applications", applications with a graphical user interface and other features of desktop software that run through a browser, while exchanging data with a remote server.

Features of an Ajax framework
Any Ajax framework is able to communicate with the server, and thus, to read data or to send its data or commands. In the last case a server-side script is required. The frameworks often add components that make use of the asynchronous communication with the server. The classical examples are buttons, tabbed panels, grids, list-boxes and other such widgets. A more innovative example, the "boxes" are more and more often implemented, and Lightbox and Slimbox are two of them. There are image galleries that place them side by side on the screen and that are making use of Ajax to display them instantaneously.
Framework may be server-driven also, and in this case, component are created on the server with a scripting language such as PHP, and sent to the browser. Ajax is used to transmit user actions to the server part, and to handle the results.
The ability to work offline as it is offered by Google Gears, may be added to the Ajax framework as well.

JavaScript libraries
Many Ajax frameworks and libraries rely solely upon JavaScript and contain no server components and therefore server technology dependencies.Most of them use XML as data format, and sometime JSON, another textual format.A JavaScript library is loaded with just a tag, as this:

This tag includes the "prototype" library into the page and its function become usable by the browser, in this page. Such Ajax libraries and frameworks include:

Prototype - http://www.prototypejs.org is the base of several other frameworks including that of Yahoo. Its goal seems to be in reducing the size of Ajax Code.

Script Aculo – http://script.aculo.us
Add more features to prototype.

Rico. – http://openrico.org/rico/home.page
Based also on prototype, add special effects to HTML pages.

Jquery – http://jquery.com
JavaScript library with Ajax support. It is equivalent to Script Aculo and uses fewer resources.

Mootools. – http://mootools.netAnother toolkit as JQuery, includes graphical effects.

Dojo Toolkit. – http://dojotoolkit.org
Uses packages with a mechanism to load them together along with the page. It can build reusable components and widgets, a lot of them is provided on the site. It allows to manipulate the DOM more easily, and to make graphical effects.

Qooxdoo. – http://qooxdoo.org
Includes advanced cross-browser layout managers and an advanced build system for graphical user interfaces similar to that of desktop software. Widgets are provided with the function to use them from the keyboard or the mouse. Third parties provide PHP or Java code to process data with XMLHttpRequest.

Yahoo UI. – http://developer.yahoo.com/yui
Library from the Yahoo search engine. Includes CSS resources.

Anaa. - http://www.anaa.edu
A simple library for GET and POST with callbacks. Implements responseHTML, the A.E.P. extension.


PHP frameworks
On the server side, the programmer may use PHP functions to process requests from the browser. PHP allows us to deal with database, search data, build pages or parts of page and publish the page or return data to the XMLHttpRequest object. PHP 5 specifically, thanks to its SimpleXML class, is able to create XML files that may be returned to the object. But all these tasks require special functions to write... however the work is already done in some free open source frameworks.

AjaxAC. – http://ajax.zervaas.com.au
Small PHP library.

Xajax. – http://www.xajaxproject.org/
More sophisticated, is made of a JavaScript library and PHP classes, to help in using other PHP functions written by you. Uses only the XML format, on the server side.

Tiny Ajax. – http://www.metz.se/tinyajax/quickstart.php
A small PHP 5 class.


Java frameworks
Java is the programming language that is the more often used to build web services.A Java framework permit to use Java web services interactively with a web page. The more commonly used are:
DWR (Direct Web Remoting) – http://getahead.org/dwr
Allows using Java functions as if they are part of the browser, from HTML code, thanks to its interface. A JavaScript part is used to update the page and another to get data with servlets.The technique is in generating in real time Java code from JavaScript code, send it to the server and run it.
Google Web Toolkit – http://code.google.com/webtoolkit/
A toolbox to develop Java applications, that are then compiled into JavaScript code, and this code processes the HTML page through DOM methods.
Legacy Java software for the web now is moving to Ajax. JavaServer Faces now includes Ajax features. ThinWire takes a unique approach in that the application is written as if it was desktop software. All the logic executes on the server, the framework encapsulates the web rendering and communication layers.


.NET frameworks
Microsoft Ajax Library - http://www.asp.net/ajax
(Formerly ATLAS) is made of a client side part: Microsoft AJAX Library, and a server side part: ASP.NET 2.0 Ajax Extensions. But a component library is also provided with graphical widgets: ASP.NET Ajax Control Toolkit.

Ajax .NET Professional- http://www.ajaxpro.info/
"Serializes" (converts and stores) .NET data to the JSON format.


ColdFusion frameworks
Libraries include:
AjaxCFC. http://www.robgonda.com/blog/projects/ajaxcfc
An object oriented framework that provides developers seamless integration between JavaScript and ColdFusion, and built-in security and debugging functions.

CFAjax. – http://www.indiankey.com/cfajax
Implements Ajax in such a way that ColdFusion method calls on the server gets executed using JavaScript a la Ajax.


Ajax and XUL
Ajax makes use of the JavaScript programming language, and XUL embeds also JavaScript into XML to define the interaction with the graphical user interface. The two systems work on the Firefox browser. The first one allows communicating with the server from a remote web page, the second one display an interface either in a local computer or through the net, with the same browser.The main difference is in the use of Canvas (HTML tag) to extend Ajax and to extend XUL, XPCom and XBL.

ZK. – http://www.zkoss.org
Framework designed for allowing Ajax and XUL to communicate.


Beyond Ajax
Some current developments will reinforce again the importance of Ajax by providing standard for RIA (Rich Internet Applications), mainly HTML 5 qui extends HTML with Web applications features and Google Gears that allows a Web application to run offline.

Sunday, December 16, 2007

Synchronous VS. Asynchronous Requests

Central object that makes Ajax, Ajax is XMLHttpRequest object and its Microsoft’s ActiveX equivalent. It is this object that allows data to be transferred asynchronously. In case you are not clear what asynchronous means, it is the ability to handle processes independently from other processes. Synchronous which is the opposite of asynchronous, then means that processes are dependent upon other processes. To illustrate let us use a classical Web page scenario.

Assume we have page A and on this page we have a number of elements, including a couple of script and style tags. With synchronous data transfer the script tag needs to be parsed before the next element is parsed. In this way then the next element to be parsed by the browser is dependent upon the script tag being parsed first. Effectively we are creating a bottleneck of one connection between Web page and browser. Style tags and link elements in the head section of the document create the same bottleneck effect. They have to be parsed one at a time before other page elements can download.

Once they have been parsed then the elements in the body section can use concurrent connections to help speed up the download process. For example, most servers handle between 2 to 4 concurrent connections between web page and browser.

Consequently, this means that 2 to 4 images or other page elements can load concurrently. Yet before that process starts what is between the head tags have to be parsed first, which can considerably delay the loading of web pages. Most particularly if you are using multiple CSS and JavaScript tags. Nearly every Web page and blog on the internet uses this method. It isn't hard to see why this may be a problem in terms of increasing page load speeds.

Asynchronously loading methods differ from this scenario because the loading processes are handled independently of each other and to a significant degree overcomes the bottle of traditional Web page design. As the previous blog shows the example of Ajax, the whole gist of this technique is to use minimal JavaScript initially and then push all the head related tags, including the rest of the JavaScript, CSS etc tags through an XMLHttpRequest object. This method uses multiple connections rather than the single one that most traditional Web pages use and consequently speeds things up considerably.

Simple Example using AJAX-JSP

The following code is a simple jsp page....save it as call.jsp


<%@page contentType="text/html"%>
<!-- The above is the page directive with attribute "contentType" which is used to get the content type of the page -->

<%@page pageEncoding="UTF-8"%>

<!-- The above is the page directive with the attribute "pageEncoding" tells us that we are working with unicode encoding within the page -->

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- We call a ajax.js javascript which makes an asynchronous request to the server -->
<script language="javascript" src="ajax.js"></script> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>JSP Page using AJAX
</title>
</head>
<body>
<a onclick="sendRequest('GET','index.jsp')"href="#">ServerDate Time:
</a>
<div id="ajax_res">Server Date Time will replace thistext.
</div>
</body>
</html>

Now lets see the actual ajax.js script as given below. This is the actual ajax related script which is used to make asynchronous request to the server using the XMLHttpRequest object.

ajax.js

function createRequestObject(){
var req; try {
// Firefox, Opera, Safari
req = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' method == 'GET'){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}

Now lets see the code for index.jsp where we get the date from the server

index.jsp

<%=new java.util.Date()%>

With these three files ie ajax.js, call.jsp and index.jsp, we can use Ajax with JSP.
Enjoy Ajaxing!!!

Monday, December 10, 2007

XMLHttpRequest - HEART OF AJAX

Common XMLHttpRequest Object Properties


Common XMLHttpRequest Object Methods









XMLHttpRequest - what it actually does is simply provide a way for your client code (usually JavaScript in your Web page) to send an HTTP request.

Instead of a user request being made of the server via, for example, a normal HTTP POST or GET request, such as would be made by submitting a form or clicking a hyperlink, an Ajax script makes a request of a server by using the Javascript XMLHTTPRequest object.

Although this object may be unfamiliar to many, in fact it behaves like a fairly ordinary javascript object. As you may well know, when using a javascript image object we may dynamically change the URL of the image source without using a page refresh. XMLHTTPRequest retrieves information from the server in a similarly invisible manner.
There are two distinct methods for instantiating an XMLHttpRequest object. For Internet Explorer, an ActiveX object is used:
var req = new ActiveXObject(“Microsoft.XMLHTTP”);
For Mozilla and Safari, it's just a native object:\
var req = new XMLHttpRequest();
Instances of the XMLHttpRequest object in all supported environments share a concise, but powerful, list of methods and properties. Table 1 shows the methods supported by Safari 1.2, Mozilla, and Windows IE 5 or later.

Common XMLHttpRequest Object Methods have been shown above in the figure::








The open() and send() methods are the ones you'll likely use most. Two required parameters are the HTTP method you intend for the request and the URL for the connection. For the method parameter, use "GET" on operations that are primarily data retrieval requests; use "POST" on operations that send data to the server, especially if the length of the outgoing data is potentially greater than 512 bytes. The URL may be either a complete or relative URL.

An important optional third parameter is a Boolean value that controls whether the upcoming transaction should be handled asynchronously. The default behavior (true) is to act asynchronously, which means that script processing carries on immediately after the send() method is invoked, without waiting for a response. If you set this value to false, however, the script waits for the request to be sent and for a response to arrive from the server. While it might seem like a good idea to wait for a response before continuing processing, you run the risk of having your script hang if a network or server problem prevents completion of the transaction. It is safer to send asynchronously and design your code around the onreadystatechange event for the request object.

Common XMLHttpRequest Object Properties have been shown above

Once a request has been sent, scripts can look to several properties that all implementations have in common


The following generic function includes branched object creation, event handler assignment, and submission of a GET request. A single function argument is a string containing the desired URL. The function assumes that a global variable, req, receives the value returned from the object constructors. Using a global variable here allows the response values to be accessed freely inside other functions elsewhere on the page. Also assumed in this example is the existence of a processReqChange() function that will handle changes to the state of the request object.
var req;
function loadXMLDoc(url)
{
Req = false;
//check the browser’s compatibility with the XMLHttpRequest Object
if (window.XMLHttpRequest && !(window.ActiveXObject))
{
try
{
req = new XMLHttpRequest();
} catch(Exception e)
{
req = false;
}
}
elseif(window.ActiveXObject)
{
try
{
req = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch(Exception e) {
try
{
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
Catch(Exception e){
req = false;
}
}
}
if(req)
{
req.onreadystatechange = processReqChange;
req.open (“GET”, url, true);
req.send (“”);
}
The following listing shows a skeletal onreadystatechange event handler function that allows processing of the response content only if all conditions are right.
function processReqChange()
{
//only if the request made is completed
if (req.readyState == 4)
{
if(req.status == 200)
{
//processing statements go here
}
else
{
alert (“problem with retrieving the XML data”+ req.statusText);
}
}
}

AJAX INTRO

INTRODUCTION TO AJAX
Ajax (Asynchronous JavaScript + XML) is a recent name coined by Jesse James Garrett of Adaptive Path. Ajax isn’t a new technology. It’s a mix of several old technologies coming together in powerful new ways.

AJAX COMPARED TO CLUNKY WEB INTERFACES

The classic web application model works like this: Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing — retrieving data, talking to various legacy systems — and then returns an HTML page to the client.
This approach makes a lot of technical sense, but it doesn’t make for a great user experience. While the server is doing its thing, what’s the user doing? That’s right, waiting. And at every step in a task, the user waits some more.


Courtesy: http://www.adaptivepath.com/ideas/essays/archives/000385.php


An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true.
Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.

When you write an application today, you have two basic choices:
Desktop applications
Web applications
Desktop applications are usually pretty fast (they're running on your computer; you're not waiting on an Internet connection), have great user interfaces (usually interacting with your operating system), and are incredibly dynamic. You can click, point, type, pull up menus and sub-menus, and cruise around, with almost no waiting around.
On the other hand, Web applications are usually up-to-the-second current and they provide services you could never get on your desktop (think about Amazon.com and eBay). However, with the power of the Web comes waiting -- waiting for a server to respond, waiting for a screen to refresh, and waiting for a request to come back and generate a new page.

Ajax attempts to bridge the gap between the functionality and interactivity of a desktop application and the always-updated Web application. You can use dynamic user interfaces and fancier controls like you'd find on a desktop application, but it's available to you on a Web application.

TECHNOLOGIES INVOLVED IN AJAX
CSS offers a way of defining reusable visual styles for web page elements. HTML is used to build Web forms and identify fields for use in the rest of your application.
JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.
DHTML, or Dynamic HTML(combination of CSS,DOM and JavaScript), helps you update your forms dynamically. You'll use div, span, and other dynamic HTML elements to mark up your HTML.
DOM, the Document Object Model, will be used (through JavaScript code) to work with both the structure of your HTML and (in some cases) XML returned from the server.
XMLHttpRequest object is the heart of AJAX. It allows web programmers to retrieve data from the web server as a background activity. The data format is typically XML but it works well with any text-based data.