all repos — h3rald @ d041f9cf66df929a4e132542a17de622365a811f

The sources of https://h3rald.com

contents/articles/what-is-ajax.html

 1
 2
 3
 4
 5
 6
 7
-----
title: "What is AJAX?"
content-type: article
timestamp: 1137047408
tags: "internet|web20|ajax|webdevelopment"
-----
<em>"The Web is changing. The 30-year-old terminal-like technology it was originally is gradually giving way to new ways of doing things. The power of AJAX allows for rich user interaction without the trouble that has bugged traditional web applications."</em>This is the introduction to the script.aculo.us[1] website, and regardless your opinion about the so-called AJAX <em>programming technique</em>, they are fundamentally right: the web is changing.  AJAX is at least one way to do things in a different way, enhancing - although arguably, in some cases -  users' browsing experience.<br /><br /><strong>Application examples</strong><br />What is AJAX then? Nothing too new, but not too old either. I'd define AJAX as the <em>rebirth of Javascript</em>, for example, it's not only Javascript we're talking about. The acronym stands for Asynchronous Javascript And XML and it already gives an idea of the fundamentals of the technology: something build on <em>asynchronous server requests and responses </em>. This may be clear to coders, but the best way to try explaining this to everyday internet users is showing some famous applications:<br /><br /><em>Gmail[2]</em>: The first example? The most famous? The most used? Perhaps. Google aimed to impress both end users and geeks with it's free, long awaited email service. What's so unusual in this webmail application?<br /><ul><br /><li>An innovative and intuitive interface, more similar to a desktop application than a traditional webpage.</li><br /><li>Rich formatting through an effective, easy-to-use editor.</li><br /><li>Online spell checker.</li><br /><li>Instant </li>(one click) email tagging, labels, contact groups etc.<br /><li>Email auto save.</li><br /></ul><br /><br /><em>Kiko[3]</em>: This is a very neat online calendar, free to use and customizable. Features include:<br /><ul><br /><li>Multiple user/contacts/events administration.</li><br /><li>Personalization of the right click menu </li>(it overrides your browser's default behavior).<br /><li>Drag and drop events across the calendar.</li><br /><li>Easily switch through different calendar views without any page refresh.</li><br />-	</ul><br /><br /><em>Writely[4]</em>: An online word processor. Although it is not as advanced as its desktop's cousins, this is a truly admirable effort to port a desktop application to the web. The service is free for now and it allows users to create, edit, share and export text documents. Among its features there are:<br /><ul><br /><li>High degree of document formatting - modify font size, style, colors, alignment, insert images and links etc.</li><br /><li>Enhanced exporting options - it can create html documents, Word documents, zip files etc.</li><br /><li>Online spell-checker.</li><br /><li>Ability to easily share and publish your work.</li><br /></ul><br /><br />This list can continue[5], as new "AJAX-powered" applications are created nearly every day. <br /><fieldset><blockquote>AJAX provides the web developer the ability to create web applications that look and feel like applications that run on the desktop. It does this by solving the 'partial update' problem. AJAX makes it possible for a web application to request data from the server (usually in response to a button click or other java script 'event') and change a part of the current page to reflect the result of the query. Prior to AJAX, if the web developer wanted to retrieve any information from the server a full page update was required. This may mean a full page load when the user clicks a help icon, spell checks a document or performs a drag and drop operation that changes data on the server. AJAX solves this problem and opens the door for a host of AJAX-powered web applications<br />There were some unconventional solutions to this problem prior to AJAX. I have ignored them for the purpose of this article as they were hacky or relied on a feature in a particular browser </blockquote></fieldset><br /><br /><strong>How does it work?</strong><br />Ajax[7] is fundamentally the union of various technologies - not something new by itself:<br /><ul><br /><li> </li>(X)HTML, CSS, etc., used as presentation layer and format the information retrieved by the server: nothing special here.<br /><li>The XMLHttpRequest</li>[8] object, which allows data exchange between client and server "silently", in an asynchronous way, without the need of refreshing and reloading a whole web page<br /><li>The Dom Object Model </li>(DOM)[9], a Object-Oriented way to represent and access HTML or XML.<br /><li>XML and XSLT used for data interchange and manipulation</li><br /></ul><br /><br />The magic is undoubtedly in the XMLHttpRequest object, originally invented by Microsoft as an ActiveX object and then made available as a standard Javascript class by Mozilla-based browsers. At least something which <em>seems</em> to be compatible with <em>most</em> browsers then.<br /><br />A necessary step in any Javascript script using the XMLHttpRequest object would be something like:<br /><br /><code><br />if (window.XMLHttpRequest) { // Mozilla, Safari, ...<br />    http_request = new XMLHttpRequest();<br />} else if (window.ActiveXObject) { // IE<br />    http_request = new ActiveXObject("Microsoft.XMLHTTP");<br />}<br /></code><br /><br />In order to have an http_request object to use later on which is independent from the browser type.<br /><br />Let's now examine an example of elementary Ajax application[10]. The following code is broken into different parts and commented, the uncommented source and a demo is available on degraeve.com[10].<br /><br />For this simple example we need to create a simple server-side script which will be called by our Ajax application. The script can be in any language, this one is in Perl.<br /><br /><code><br />#!/usr/bin/perl -w<br />use CGI;<br /><br />$query = new CGI;<br /><br />$secretword = $query-param('w');<br />$remotehost = $query-remote_host();<br /><br />print $query-header;<br />print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>.<br /> </code><br /><br />Basically it creates a new CGI object named $query, used to access the parameter which will be passed by our submission form, "w", and get the user's IP address.<br />The script will then print a the page header and a phrase containing the word entered in our form and the user's IP address.<br /><br />And here's the simple Ajax application:<br /><br /><code><br /><html><br /><head><br /><title>Simple Ajax Example</title><br /><br /><script language="Javascript"><br /></code><br /><br /><em>Comment: Just the first HTML tags of the page, and the beginning of the script</em><br /><br /><code><br />function xmlhttpPost(strURL) {<br />    var xmlHttpReq = false;<br />    var self = this;<br />    // Mozilla/Safari<br />    if (window.XMLHttpRequest) {<br />        self.xmlHttpReq = new XMLHttpRequest();<br />    }<br />    // IE<br />    else if (window.ActiveXObject) {<br />        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");<br />    }<br /></code><br /><br /><em>Comment: First of all we create a function named xmlhttpPost, which takes the parameter strURL, i.e. the web address of the script we created earlier. In the first part of the function, we create the HTMLHttpRequest object independently of the browser, which in this case is called self.xmlHttpReq. </em><br /><code><br /> <br />    self.xmlHttpReq.open('POST', strURL, true);<br /><br />    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');<br /></code><br /><br /><em>Comment: with the method open we initialize the connection, specifying that we want to send a POST request to the page "strURL" and that the connection is asynchronous (true). The third parameter is actually true by default and could have been omitted in this case. <br />As we want to use the POST method, we need to set the content-type header for our request, in this case "application/x-www-form-urlencoded". </em><br /><br /><code><br />    self.xmlHttpReq.onreadystatechange = function() {<br />        if (self.xmlHttpReq.readyState == 4) {<br />            updatepage(self.xmlHttpReq.responseText);<br />        }<br />    }<br />    self.xmlHttpReq.send(getquerystring());<br />}<br /></code><br /><br /><br /><em>Comment: This is the crucial part, as we need to send the request and also define the behavior of our application once the response is received. The request is sent using the "send" method, which sends a properly formatted query string (see below), but before that we need to setup a "listener" to monitor what happens to our request.<br />The readyState variables is updated according to the status of the connection, and can assume the following values:<br /><ul><br /><li>0 - Uninitialised</li><br /><li>1 - Loading</li><br /><li>2 - Loaded</li><br /><li>3 - Interactive</li><br /><li>4 - Completed</li><br /></ul><br /><br />We want to update our page once we are sure that the connection with the script has been established, therefore we setup a listener (onreadystatechange) to update the page via the function update page defined below only if the connection's state is "Completed" (self.xmlHttpReq.readyState == 4). The  self.xmlHttpReq.responseText variable which is sent to the update page function contains the response generated by our CGI script. </em><br /><br /><code><br />function getquerystring() {<br />    var form     = document.forms['f1'];<br />    var word = form.word.value;<br />    qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring<br />    return qstr;<br />}<br /></code><br /><br /><em>Comment: This function simply formats the parameter sent to the script as "w=typedword" where "typedword" is the word typed in the form of our application. </em><br /><br /><code><br />function updatepage(str){<br />    document.getElementById("result").innerHTML = str;<br />}<br /></code><br /><br /><em>Comment: Finally, this function inserts the response we got from the CGI script into an HTML element with id=result, through the method innerHTML. </em><br /><br /><code><br /></script><br /></head><br /><br /><form name="f1"><br />  <pword: <input name="word" type="text"  ><br />  <input value="Go" type="button" >onclick='JavaScript:xmlhttpPost("/cgi-bin/simple-ajax-example.cgi")'</p><br />  <div id="result"></div><br /></form><br /></body><br /></html><br /></code><br /><br /><em>Comment: This is the final part of the application, which defines our form containing a text field and a submit button. Note that our xmlhttpPost function is called once the button is clicked, through the on click attribute. </em><br /><br />That's it. <br />The first reaction after reading so far would probably be "Ajax is not easy at all", well, I never said it was. To create a simple application which just prints something on the screen we had to go through a lot of code, and we could have done something similar with much less hassle. This was just a trivial example, very different from those large scale applications available online.<br /><br />There's good news though, there are plenty of frameworks and toolkits which makes life easier for developers interested in using this programming technique. There are in particular various libraries built upon the Prototype[11] framework such as the already mentioned Script.aculo.us[1] and Rico[12] for examples, and various frameworks which integrate Ajax in some way in any server side language, like Ruby on Rails[13] or CakePHP[14], for example.<br /><br /><strong>Conclusion</strong><br />Undoubtedly Ajax can be used to create really powerful and innovative applications, but it shouldn't be abused or mis-used. There are a few things to keep in mind, when developing an Ajax application:<br /><ul><br /><li>It requires Javascript to be enable on the client browser, and the developer obviously can't control that</li><br /><li>The application may not compatible with all browsers, in particular older browsers will definitely not be able to access it.</li><br /><li>It can be too much of a surprise for the user who never used an Ajax application before: it may experience delays in responses, some basic functionalities like the "Back" button might not work as expected etc.</li><br /></ul><br /><br />There are actually many more things to consider [15] before even start planning to develop an application, and can basically be summarized as follows:<br /><br /><em>"Do not use Ajax in your web application unless you know what you're doing"</em><br /><br />Luckily, there are a lot of articles and resources[16] out there, waiting for you.<br /><br /><br /><strong>Notes and Resources</strong><br /><small><br />[1] Script.aculo.us AJAX toolkit: <a href="http://www.script.aculo.us ">http://www.script.aculo.us </a><br />[2] Gmail - Google's online webmail: <a href="http://mail.google.com/mail">http://mail.google.com/mail</a><br />[3] Kiko  - Online calendar: <a href="http://www.kiko.com/">http://www.kiko.com/</a><br />[4] Writely - Online word processor: <a href="http://www.writely.com/">http://www.writely.com/</a> <br />[5] A venture forth Blog - Top 10 Ajax applications: <a href="http://www.aventureforth.com/?p=13">http://www.aventureforth.com/?p=13</a><br />[6] HTTP - Webopedia entry: <a href="http://www.webopedia.com/TERM/H/HTTP.html">http://www.webopedia.com/TERM/H/HTTP.html</a><br />[7] AJAX - Wikipedia Page: <a href="http://en.wikipedia.org/wiki/AJAX">http://en.wikipedia.org/wiki/AJAX</a><br />[8] XMLHTTP Wikipedia Page: <a href="http://en.wikipedia.org/wiki/XMLHTTP">http://en.wikipedia.org/wiki/XMLHTTP</a><br /><br />[9] Dom Object Model - Wikipedia Page: <a href="http://en.wikipedia.org/wiki/Document_Object_Model">http://en.wikipedia.org/wiki/Document_Object_Model</a><br />[10] degraeve.com - Simple Ajax Example: <a href="http://www.degraeve.com/reference/simple-ajax-example.php">http://www.degraeve.com/reference/simple-ajax-example.php</a><br />[11] Prototype Javascript Framework: <a href="http://prototype.conio.net/">http://prototype.conio.net/</a><br />[12] Rico open-source Javascript library: <a href="http://openrico.org/">http://openrico.org/</a><br />[13] Ruby on Rails: <a href="http://www.rubyonrails.org">http://www.rubyonrails.org</a><br />[14] CakePHP framework: <a href="http://www.cakephp.org">http://www.cakephp.org</a><br />[15] Alex Bosworth's Weblog: Ajax Mistakes: <a href="http://sourcelabs.com/ajb/archives/2005/05/ajax_mistakes.html">http://sourcelabs.com/ajb/archives/2005/05/ajax_mistakes.html</a><br />[16] AjaxMatters.com: <a href="http://www.ajaxmatters.com/r/welcome">http://www.ajaxmatters.com/r/welcome</a><br /></small><br />