Friday, September 9, 2011

INTRODUCTION TO AJAX


Using JavaScript technology, an HTML page can asynchronously make calls to the server from which it was loaded and fetch content that may be formatted as XML documents, HTML content, plain text, or JavaScript Object Notation (JSON). The JavaScript technology may then use the content to update or modify the Document Object Model (DOM) of the HTML page. The term Asynchronous JavaScript Technology and XML ( Ajax) has emerged recently to describe this interaction model.

Ajax is not new. These techniques have been available to developers targeting Internet Explorer on the Windows platform for many years. Until recently, the technology was known as web remoting or remote scripting. Web developers have also used a combination of plug-ins, Java applets, and hidden frames to emulate this interaction model for some time. What has changed recently is the inclusion of support for the XMLHttpRequest object in the JavaScript runtimes of the mainstream browsers. The real magic is the result of the JavaScript technology's XMLHttpRequest object.
           
Although this object is not specified in the formal JavaScript technology specification, all of today's mainstream browsers support it. The subtle differences with the JavaScript technology and CSS support among current generation browsers such as Mozilla Firefox, Internet Explorer, and Safari are manageable. JavaScript libraries such as Dojo, Prototype, and the Yahoo User Interface Library have emerged to fill in where the browsers are not as manageable and to provide a standardized programming model. Dojo, for example, is addressing accessibility, internationalization, and advanced graphics across browsers -- all of which had been thorns in the side of earlier adopters of Ajax. More updates are sure to occur as the need arises.

What makes Ajax-based clients unique is that the client contains page-specific control logic embedded as JavaScript technology. The page interacts with the JavaScript technology based on events such as the loading of a document, a mouse click, focus changes, or even a timer. Ajax interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in bite-size pieces to be displayed. Ajax will require a different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event resulting in a call to the server. The clients would then refresh and re-render the complete HTML page for each response. Rich web applications focus on a client fetching an HTML document that acts as a template or container into which to inject content, based on client events using XML data retrieved from a server-side component.

If anything about current interaction design can be called “glamorous,” it’s creating Web applications. After all, when was the last time you heard someone rave about the interaction design of a product that wasn’t on the Web? (Okay, besides the iPod.) All the cool, innovative new projects are online.
Despite this, Web interaction designers can’t help but feel a little envious of our colleagues who create desktop software. Desktop applications have a richness and responsiveness that has seemed out of reach on the Web. The same simplicity that enabled the Web’s rapid proliferation also creates a gap between the experiences we can provide and the experiences users can get from a desktop application.
That gap is closing. Take a look at Google Suggest. Watch the way the suggested terms update as you type, almost instantly. Now look at Google Maps. Zoom in. Use your cursor to grab the map and scroll around a bit. Again, everything happens almost instantly, with no waiting for pages to reload.
Google Suggest and Google Maps are two examples of a new approach to web applications that we at Adaptive Path have been calling Ajax. The name is shorthand for Asynchronous JavaScript + XML, and it represents a fundamental shift in what’s possible on the Web.

DEFINING AJAX



Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
§  standards-based presentation using XHTML and CSS;
§  dynamic display and interaction using the Document Object Model;
§  data interchange and manipulation using XML and XSLT;
§  asynchronous data retrieval using XMLHttpRequest;
§  and JavaScript binding everything together.
Figure 1: The traditional model for web applications (left) compared to the Ajax model (right).

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, crunching numbers, talking to various legacy systems — and then returns an HTML page to the client. It’s a model adapted from the Web’s original use as a hypertext medium, but as fans of The Elements of User Experience know, what makes the Web good for hypertext doesn’t necessarily make it good for software applications.
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.
Obviously, if we were designing the Web from scratch for applications, we wouldn’t make users wait around. Once an interface is loaded, why should the user interaction come to a halt every time the application needs something from the server? In fact, why should the user see the application go to the server at all?

How Ajax is Different
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.
Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesn’t require a trip back to the server — such as simple data validation, editing data in memory, and even some navigation — the engine handles on its own. If the engine needs something from the server in order to respond — if it’s submitting data for processing, loading additional interface code, or retrieving new data — the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application.
Figure 2: The synchronous interaction pattern of a traditional web application (top) compared with the asynchronous pattern of an Ajax application (bottom).

HISTORY OF AJAX


New technology quickly becomes so pervasive that it’s sometimes hard to remember what things were like before it. The latest example of this in miniature is the technique known as Ajax, which has become so widespread that it’s often thought that the technique has been around practically forever.
In some ways it has. During the first big stretch of browser innovation, Netscape added a feature known as LiveScript, which allowed people to put small scripts in web pages so that they could continue to do things after you’d downloaded them. One early example was the Netscape form system, which would tell you if you’d entered an invalid value for a field as soon as you entered it, instead of after you tried to submit the form to the server.
LiveScript became JavaScript and grew more powerful, leading to a technique known as Dynamic HTML, which was typically used to make things fly around the screen and change around in response to user input. Doing anything serious with Dynamic HTML was painful, however, because all the major browsers implemented its pieces slightly differently.
Shortly before web development died out, in early versions of Mozilla, Netscape showed a new kind of technique. I don’t think it ever had a name, but we could call it Dynamic XML. The most vivid example I remember seeing was a mockup of an Amazon.com search result. The webpage looked just like a typical Amazon.com search result page, but instead of being written in HTML it was a piece of XML data which was then rendered for the user by a piece of JavaScript. The cool part was that this meant the rendering could be changed on the fly — there were a bunch of buttons that would allow you to sort the books in different ways and have them display using different schemes.
Shortly thereafter the bubble burst and web development crashed. Not, however, before Microsoft added a little-known function call named XMLHttpRequest to IE5. Mozilla quickly followed suit and, while nobody I know used it, the function stayed there, just waiting to be taken advantage of.
XMLHttpRequest allowed the JavaScript inside web pages to do something they could never really do before: get more data.1 Before, all the data either had to be sent with the web page. If you wanted more data or new data, you had to grab another web page. The JavaScript inside web pages couldn’t talk to the outside world. XMLHttpRequest changed that, allowing web pages to get more data from the server whenever they pleased.
Google was apparently the first to realize what a sea change this was. With Gmail and Google Maps, they built applications that took advantage of this to provide a user interface that was much more like a web application. (The startup Oddpost, bought by Yahoo, actually predated this but their software was for-pay and so they didn’t receive as much attention.)
With Gmail, for example, the application is continually asking the server if there’s new email. If there is, then it live updates the page, it doesn’t make you download a new one. And Google Maps lets you drag a map around and, as you do so, automatically downloads the parts of it you want to look at inline, without making you wait for a whole new page to download.
Jesse James Garrett of Adaptive Path described this new tactic as Ajax (Asynchronous Javascript And XML) in an essay and the term immediately took off. Everyone began using the technique in their own software and JavaScript toolkits sprung up to make doing so even easier.
Both systems were relatively ill-supported by browsers in my experience. They were, after all, hacks. So while they both seemed extremely cool (KnowNow, in particular, had an awesome demo that allowed for a WYSIWYG SubEthaEdit-style live collaboration session in a browser), they never really took off.
Now apparently there is another technique, which I was unaware of, that involved changing the URL of an iframe to load new JavaScript. I’m not sure why this technique didn’t quite take off. While Google Maps apparently used it (and Oddpost probably did as well), I don’t know of any other major users.

TECHNOLOGIES USED IN AJAX


The term Ajax has come to represent a broad group of web technologies that can be used to implement a web application that communicates with a server in the background, without interfering with the current state of the page. In the article that coined the term Ajax, Jesse James Garrett explained that the following technologies are incorporated:
§  HTML or XHTML and CSS for presentation
§  the Document Object Model (DOM) for dynamic display of and interaction with data
§  XML for the interchange of data, and XSLT for its manipulation
§  the XMLHttpRequest object for asynchronous communication
§  PHP or another scripting language may be used on the server
§  JavaScript to bring these technologies together
§  SOAP may be used to dialog with the server.
Since then, however, there have been a number of developments in the technologies used in an Ajax application, and the definition of the term Ajax. In particular, it has been noted that JavaScript is not the only client-side scripting language that can be used for implementing an Ajax application; other languages such as VBScript are also capable of the required functionality. (However, JavaScript is the most popular language for Ajax programming due to its inclusion in and compatibility with the majority of modern web browsers.) Also, XML is not required for data interchange and therefore XSLT is not required for the manipulation of data. JavaScript Object Notation (JSON) is often used as an alternative format for data interchange,] although other formats such as preformatted HTML or plain text can also be used

AJAX IN DEPTH


Why use Ajax?
Mainly to build a fast, dynamic website, but also to save resources.
For improving sharing of resources, it is better to use the power of all the client computers rather than just a unique server and network. Ajax allows to perform processing on client computer (in JavaScript) with data taken from the server.
The processing of web page formerly was only server-side, using web services or PHP scripts, before the whole page was sent within the network.
But Ajax can selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all images, menus, etc...
For example, fields of forms, choices of user, may be processed and the result displayed immediately into the same page.
Who’s Using Ajax
Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year — Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps — are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar techniques.
These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn’t another technology that only works in a laboratory. And Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.
At Adaptive Path, we’ve been doing our own work with Ajax over the last several months, and we’re realizing we’ve only scratched the surface of the rich interaction and responsiveness that Ajax applications can provide. Ajax is an important development for Web applications, and its importance is only going to grow. And because there are so many developers out there who already know how to use these technologies, we expect to see many more organizations following Google’s lead in reaping the competitive advantage Ajax provides.
What is Ajax in depth?
Ajax is a set of technologies, supported by a web browser, including these elements:
·     HTML and CSS for presenting.
·     JavaScript (ECMAScript) for local processing, and DOM (Document Object Model) to access data inside the page or to access elements of XML file read on the server (with the getElementByTagName method for example)...
·     The XMLHttpRequest object is used to read or send data on the server asynchronously.
Optionally...
·     DOMParser may be used
·     PHP or another scripting language may be used on the server.
·     XML and XSLT to process the data if returned in XML form.
·     SOAP may be used to dialog with the server.
The "asynchronous" word, means that the response of the server while be processed when available, without to wait and to freeze the display of the page. 

HOW TO AJAX ?


How does it works?
Ajax uses a programming model with display and events. These events are user actions, they call functions associated to elements of the web page.
Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server.
To get data on the server, XMLHttpRequest provides two methods:
- open: create a connection.
- send: send a request to the server.
Data furnished by the server will be found in the attributes of the XMLHttpRequest object:
- responseXml for an XML file or
- responseText for a plain text.

Take note that a new XMLHttpRequest object has to be created for each new file to load.

We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyState attribute of XMLHttpRequest.

States of readyState follow (only the last one is really useful):
0: not initialized.
1: connection established.
2: request received.
3: answer in process.
4: finished.


Ajax and DHTML
Dynamic HTML has same purpose and is a set of standards:
- HTML,
- CSS,
- JavaScript.
DHTML allows to change the display of  page from user commands or from text typed by user.
Ajax allows also to send requests asynchronously and load data from the server. It is DHTML plus the XHR object.
The XMLHttpRequest object
Allows to interact with the servers, thanks to its methods and attributes.
Attributes
readyState
the code successively changes value from 0 to 4 that means for "ready".
Status
200 is OK
404 if the page is not found.
responseText
holds loaded data as a string of characters.
responseXml
holds an XML loaded file, DOM's method allows to extract data.
onreadystatechange
property that takes a function as value that is invoked when the readystatechange event is dispatched.
Methods
open(mode, url, boolean)
mode: type of request, GET or POST
url: the location of the file, with a path.
boolean: true (asynchronous) / false (synchronous).
optionally, a login and a password may be added to arguments.
send("string")
null for a GET command.
Building a request, step by step
First step: create an instance
This is just a classical instance of class, but two options must be tried, for browser compatibility.
if (window.XMLHttpRequest)     // Object of the current windows
{
    xhr = new XMLHttpRequest();     // Firefox, Safari, ...
}
else
 if (window.ActiveXObject)   // ActiveX version
 {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer
 }
Or exceptions may be used instead:
try {
   xhr = new ActiveXObject("Microsoft.XMLHTTP");    // Trying Internet Explorer
}
catch(e)    // Failed
{
  xhr = new XMLHttpRequest();    // Other browsers.
}
Second step: wait for the response
The response and further processing are included in a function and the return of the function will be assigned to the onreadystatechange attribute of the object previously created.
xhr.onreadystatechange = function() { // instructions to process the response };                  
if (xhr.readyState == 4)
{
   // Received, OK
} else
{
  // Wait...
}
Third step: make the request itself
Two methods of XMLHttpRequest are used:
- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.
The request below read a document on the server.
xhr.open('GET', 'http://www.xul.fr/somefile.xml', true);                 
xhr.send(null);
Examples
Get a text
<html>
<head>
<script>
function submitForm()
{
    var xhr;
    try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
    catch (e)
    {
        try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
        catch (e2)
        {
          try {  xhr = new XMLHttpRequest();     }
          catch (e3) {  xhr = false;   }
        }
     }
 
    xhr.onreadystatechange  = function()
    {
         if(xhr.readyState  == 4)
         {
              if(xhr.status  == 200)
                  document.ajax.dyn="Received:"  + xhr.responseText;
              else
                 document.ajax.dyn="Error code " + xhr.status;
         }
    };

   xhr.open(GET, "data.txt",  true);
   xhr.send(null);
}
</script>
</head>
                
<body>
    <FORM method="POST" name="ajax" action="">                 
         <INPUT type="BUTTON" value="Submit"  ONCLICK="submitForm()">
         <INPUT type="text" name="dyn"  value="">
    </FORM>
 </body>
 </html>
Syntax of form using Ajax
View a demo of the example in action.
Download the source.

Comments on the code:
new ActiveXObject(Microsoft.XMLHTTP)
   This constructor is for Internet Explorer.

new XMLHttpRequest()
   This constructor is for any other browser including Firefox.

http.onreadystatechange

  An anonymous function is assigned to the event indicator.

http.readyState == 4
   The 4 state means for the response is ready and sent by the server.

http.status == 200
   This status means ok, otherwise some error code is returned, 404 for example.

http.open( "POST", "data.xml", true);
   POST or GET
   URL of the script to execute.
   true for asynchronous (false for synchronous).

http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   This is for POST only.

http.send(document.getElementById("TYPEDTEXT").value);
   Send data to the server. Data comes from the "TYPEDTEXT" variable filled throught the form by the user.

Get from XML
To get data from an XML file, we have just to replace this line:
document.ajax.dyn="Received:" + xhr.responseText;
by this code:
var doc = xhr.responseXML;   // Assign the XML file to a var
var element = doc.getElementsByTagName('root').item(0);   // Read the first element
document.ajax.dyn.value= element.firstChild.data;    // Assign the content to the form
View a demo of the get from XML example in action.



Write to body
In this demo, the text read is put into the body of the page, and not into a textfield.
The code below replaces the textfield form object and the second part replaces the assignment into the JavaScript function.
<div id="zone">
     ... some text to replace ...
 </div>
document.getElementById("zone").innerHTML = "Received:" + xhr.responseText;                        

Post a text
In this demo, a text is sent to the server and is written into a file. The call to the "open" method changes, the argument is POST, the url is the name of a file or script that receives the data sent, and that must process it. And the "send" method has now a value as argument that is a string of parameters.
xhr.open("POST", "ajax-post-text.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                 
xhr.send(data);
The parameter of the send method is in the format of the HTML POST method. When several values are sent, they are separated by the ampersand symbol:
var data = "file=" + url + "&content=" + content;
The "file" parameter is the name of a file created to store the content. The filename must be checked by the server to prevent any other file to be modified.
Using an external file
It is simpler to include a JavaScript file. This line will be included into the head section of the HTML page:
<script src="ajax.js" type="text/javascript"></script>
And the function is called with this statement:
var xhr = createXHR();
View the script in the ajax.js file.

How to build an Ajax website?
You need for some wrapper. A short list of frameworks is provided below.
Your JavaScript program, integrated into a web page, sends request to the server to load files for rebuilding of pages. The received documents are processed with Dom's methods or XML parsers and the data are used to update the pages.