Docstoc

AJAX

Document Sample
AJAX Powered By Docstoc
					AJAX
Asynchronous Javascript And XML


The ability to partially update a web page instead of requiring a complete
refresh of that page can be used to give the end user a richer and fuller
experience more in-line with what they expect with a desktop application.
Ajax is the term being used to claim such is possible with a web application
when using the XMLHttpRequest API, JavaScript, and the document object
model. This paper attempts to explain how the term AJAX came into being
and what core technologies are behind it and how they are all tied together.
It concludes that every web developer should understand the idea behind
AJAX and understand just how useful it can be.




Cordell C. Davidson                    7/25/2007
Cordell Davidson is a Certified Public Accountant (CPA) with a fondness for technology. He
first begin working with Ashton-Tates dBase PC based database system in the late 1980‟s and
eventually worked as a C programmer on tax preparation software and as an Oracle DBA with
a software development company specializing in ERP solutions. He has also managed various
technical departments, taught technical classes for both in-house and external clients, been the
IT Director of a division of a Fortune 200 company and provided technical consulting services
to clients across the country. He is presently attending the University of South Alabama
pursuing a master‟s degree in Computer Science in order to learn about all the things he has
been working with over the last twenty years.
                                                                                     7/8/2007




AJAX
Asynchronous Javascript And XML




Introduction

When Linux-Apache-MySQL-PHP and/or Perl technologies are used in conjunction with one
another, the term LAMP application is often used to refer to the application created. In a
similar manner, the term AJAX refers to not just one technology but several that work
together to achieve a goal. The AJAX acronym flows from the first letters in the group of
technologies described as „Asynchronous Javascript And XML‟ which is the topic of this
paper.

Over the last few years, this term AJAX has become familiar with many developers of web
applications. Google, for example, has implemented both Gmail and Google Maps using
AJAX as a core technology (Murray, Greg, 2006). Gmail uses the technology to allow it to
update the inbox automatically whenever new mail is received. The end user no longer is
required to press the refresh button to check for new mail. Instead, the process is automated
for him. Google Maps allow the user to „grab‟ the map and move it around the screen where it
is updated almost instantly.

Both of these web applications compare favorably with standalone desktop applications in
speed of updates and a rich user interaction. Though it has happened gradually, the point is
being reached where web applications do not necessarily need to sacrifice responsiveness for
mobility and portability.

Much of this success is due to the use of AJAX, yet many developers and other professionals
have never been exposed to the technology and cannot really explain what it is, how it is
implemented, or what it can be used for.




Historical Perspective

There are many different ways of presenting a web page and there are many different ways
of updating that web page. In the early days of the World Wide Web (WWW), for example, all
content was static. A page was served to the client and that was pretty much it. From what I




                                                                                           1
                                                                                       7/8/2007


remember from those early days (1995 or so), that was enough. It was cool and following
links from one site to another was an amazingly easy way to waste an entire day.

Enterprising companies and individuals soon found that they needed a better way of
interacting with all these people that were coming to their web sites. It was not long before
common gateway interface (CGI) scripts were running and processing variables passed in
from a client‟s browser and returning updated web pages. This solved the immediate need
but the user wanted an even better experience on her end. Something in line with the user
interface and application responsiveness they received from their desktop applications was
needed.

Neither the client nor the server side technologies were standing still. PHP, Java Servlets,
ASP, JSP, Java Beans, application servers, ASP.NET, and more technologies evolved or were
invented to run in conjunction with ever more powerful web servers. Java applets,
Javascript, VBScript, Jscript, improved (though often incompatible) browsers, evolving
HTML standards, the document object model (DOM) for each browser, and other
technologies were developed to improve the users experience. One of these was an HTML
element called an in-line frame or IFRAME which when combined with a browsers DOM
opened up new ways of doing things.

The in-line frame (HTML IFRAME) allows one HTML page to be embedded within another
one and the browsers document object model (DOM) treated a page in a hierarchal tree based
manner and allowed easier searching, retrieving, and updating of individual elements within
the page. Before long, developers realized that they could make this frame invisible and then
use it to gather data from the server to update the page the user could see via the document
object model. Often this required a kludge of Javascript and HTML and was often ridiculed
as spaghetti code (from what I recall) but it did work. Dynamic HTML (DHTML) with hidden
frames was the term given to such web pages because the developer could dynamically
update a web page or check for data entry errors as the end-user entered data into a form, for
example. The client‟s web experience was greatly improved though still not as richly
interactive as a stand-alone application might be.

In 2000, Microsoft developed a new technology for asynchronous communication from a
client‟s web page to the server that was providing the content. The concept eventually
evolved into the XMLHttpRequest (XHR) object and, with some variation, is available to be
used with most major current browsers (Remote Scripting, 2007). This allows data
transmission between the client and the server to be made asynchronously (if required).The
use of such technology with XML and Javascript was coined into the term AJAX by Jesse
James Garrett in 2005. In the article he published, he explained how such technology was
being used to solve complex problems and how he came up with the name to help him sell his
solutions to a client (Garrett, James, 2005). Two years later, it is heard everywhere. Books,
training seminars, and all sorts of other information are now available.




AJAX Components



                                                                                                2
                                                                                       7/8/2007


This paper explains the components of AJAX, how they work together and why it might be
good to understand more about what it can do for the web developer. The audience is
assumed to be readers with a core competency in computer science or a related field but no
particular exposure to AJAX is assumed.

The term AJAX was coined in 2005 by Jesse James Garrett as a descriptive term and a
marketing tool used by his company when communicating with clients. The term is an
acronym that stands for Asynchronous JavaScript and XML. Specifically, he said: “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.” (Garrett, James, 2005)


The wikipaedia.com entry on Ajax Programming says that “Ajax is asynchronous in that
loading does not interfere with normal page loading. JavaScript is the programming
language that Ajax function calls are made in. Data retrieved using the technique is
commonly formatted using XML, as reflected in the naming of the XMLHttpRequest object
from which Ajax is derived.” (Ajax (programming), 2007)

Garrets‟ vision, and I paraphrase his article, was that user interaction via a client‟s browser
and a web site could be more like what a user experienced with their desktop applications. A
full refresh of the screen should not be required if only on field on a form, for example,
changed. However, the classic web model worked exactly like that. An action on the users
interface triggers an HTTP request to the server which eventually returns a web page back
to the client which often just updates the page they were already on. It is not a new page but
an updated page. During this update, however, the client must often wait, doing nothing,
while the page is retrieved. The users experience could be improved if information could be
passed asynchronously back and forth between the client and the server and only update
what needed to be updated on the client instead of refreshing the entire page. This could be
done with current technology but few people understood how to do this. The term AJAX (also
called Ajax) was given to put a name to the use of these technologies when used together.
(Garrett, James, 2005).

As mentioned above, Ajax uses XHTML, Cascading Style Sheets (CSS), the document object
model (DOM), XML and XLST, JavaScript and the XMLHttpRequest object. HTML is often
used instead of XTML, CSS is not strictly required, and JSON or HTML is often used for the
data component instead of XML. The core requirement for Ajax is the ability for the client
and the server to be able to talk asynchronously. This is provided through the
XMLHttpRequest object though even that object can be simulated by the use of the inline
frames capability of HTML. Finally, a browser of some sort must be used. The next few
paragraphs will provide a brief description of these technologies and how they are used with
Ajax.




                                                                                             3
                                                                                       7/8/2007


HTML is described in the 4.01 specification as “a universally understood language, a kind of
publishing mother tongue that all computers may potentially understand. The publishing
language used by the World Wide Web is HTML (from HyperText Markup Language)”
(HTML 4.01 Specification, 1999). XHTML is often called the successor to HTML and is very
similar. Some noticeable differences, though, are that all markups must be written in lower
case, that every tag must be closed, and that attribute values in tags must be quoted
(Markup Language, 2007). Because of the similarities and because not all browsers yet
support XHTML, many authors write HTML in XHTML format but specify HTML as the
doctype in the header of the document. This helps to ensure that the document is well formed
and that the document object model (DOM) is correct. (Keith, 2007) This, in turn, keeps the
document accessible for use via Ajax.

The document object model (DOM) was first specified with HTML 4 and is a very important
piece of Ajax. The DOM presents the structure of web pages as a set of programmable objects
that can be manipulated by JavaScript. Previous to specifications of the DOM by the World
Wide Web Consortium (W3C), most browsers included their own, proprietary, document
object model which meant that any code written to access a document displayed in one
browser would need to be rewritten or at least have code branches for any other browsers
that might be used with the document. All major browsers now support the W3C DOM
specification which makes portability much easier (Crane, Pascarello, & James, 2006). “The
Document Object Model is a platform- and language-neutral interface that will allow
programs and scripts to dynamically access and update the content, structure and style of
documents. The document can be further processed and the results of that processing can be
incorporated back into the presented page” (DOM, 2005).

Cascading Style Sheets (CSS) is a stylesheet language that describes the presentation of a
document written in a markup language. In particular, it is used to define aspects of the
presentation of web pages and to enable separation of the content of a page from the how
that page is presented. HTML can be used to change the font, color, style, or layout of a page
but it is considered to be less complex and more flexible to use CSS for this purpose (CSS,
2007). Though CSS is not a requirement for use with Ajax, it is considered good form. By
abstracting out the presentation aspects of the page from the content, then either the content
or the presentation can be changed without impacting the other with less chance for error
being introduced.

JavaScript is a general purpose programming language. A web browser provides a
JavaScript interpreter which allows a programmer access to the browsers internal
capabilities. Since the DOM is one of these capabilities, JavaScript is used in Ajax to traverse
the nodes of the document tree and to access individual node elements and even process
events of these nodes. Dynamic HTML is a term used by some to describe the combination of
HTML, style sheets and scripts that allows documents to be animated. When these tools are
used along with an XMLHttpRequest object, the term Ajax is more appropriately applied.
With Ajax, JavaScript can instantiate an XMLHttpRequest object to communicate
asynchronously with the server, accept and transform any data returned, and update only a
portion of the web page in contrast to the full refresh required in the past. (Negrino &
Smith, 2004).




                                                                                              4
                                                                                       7/8/2007


“ XMLHttpRequest(XHR) is an API that can be used by JavaScript, and other web browser
scripting languages to transfer XML and other text data to and from a web server using
HTTP, by establishing an independent communication channel between a web page's Client-
Side and Server-Side” (XMLHttpRequest, 2007). Until version 7 of Internet Explorer (IE),
there were two possible versions of this object. There was one created by Microsoft (who
actually invented the technology) and one created by vendors of the other major browsers.
This requires that a test be made to determine which version of the object is being created
before actually making the call. With version 7 of IE , however, Microsoft has changed the
object to conform with the rest of the browser community (Keith, 2007). By allowing
asynchronous calls between the server and the client, this API paved the way for what has
become known as Ajax today. With this tool, a programmer can keep a communications line
open and, in conjunction with JavaScript and DOM, update a portion of a web page without
requiring the entire page be refreshed. Though the API includes XML as part of its name,
XML is not specifically required for data. It can handle XML, JSON, HTML, or any other
text.

As briefly mentioned in the historical section of this paper, before XHR was invented or
became popular, it was common for many sites to use the inline frames (IFRAME) feature of
HTML to give users some of the same benefits of asynchronous requests. They would do this
by hiding the IFRAME and then having that frame refreshed with updated data when
appropriate. Then they would use DHTML to update the page the user could see. As far as
the user was concerned, the update occurred asynchronously. Some developers see little
difference in using this method over the use of asynchronous calls and for small documents
that is probably true. However, there is little argument that the ability to make
asynchronous calls to and from the server has greatly impacted the scalability of larger sites.
(Keith, 2007)

XML stands for eXtensible Markup Language and is a general-purpose markup language
that allows its users to define their own tags to extend the language. It is used by many
systems to pass data in a human readable format. It stores data in a tree structure that can
also be easily traversed by programs. As such, it has become very popular for use with
internet applications (XML, 2007). Even though XML is included as part of the name of Ajax,
it is not a requirement. Data can be sent as XML, JSON, HTML, or any other type of text.

JSON stands for JavaScript Object Notation. “It is a text-based, human-readable format for
representing objects and other data structures and is mainly used to transmit such
structured data over a network connection” (JSON, 2007). It is often used in Ajax
programming as an alternative to XML as many JavaScript developers find it more familiar
than XML and easier to use. When used with XMLHttpRequest, the returned text is passed
to the JavaScript eval function where the text can be executed as JavaScript and placed
directly into JavaScript variables. There can be some potential security issues with this
method however, as executable JavaScript code can be returned. (JSON, 2007)

Below, is shown Figure 1 which is a simplistic view of a client server architecture as used
with most web sites. A client asks for a particular page and the server retreives the page and
sends it to th client. If the page has to be updated, the client asks the server for the updated
data. Before AJAX was introduced, this usually meant that the entire page would be
refreshed even if only a small portion of the page had changed. The client may have to wait


                                                                                              5
                                                                                     7/8/2007


until the server can process the request because that is how synchronous communications
work. The client asks and then waits, or blocks, untill the server returns the requested
information. With asynchrounous communications, the client asks for data from the server
and then goes on and does other useful work. When the request is complete, the server
communicates back to the client via a callback mechanism to pass the information back to
the client.




       Figure 1 – Client Server communications

Ajax can use either synchronous communications but its ability to communicate
asynchronously is what gives it its power. For example, a request can be made to load all the
potential images which may be clicked upon in an interactive map. This can be done in the
background while the user is focused upon locating the intersection she is interested in.
When she clicks on the intersection to bring up a more detailed map, the images have
already been loaded and can be shown instantly. The user does not have to wait for all of
these graphic images to be retrieved from the server and displayed while she watches the
hourglass icon spin. To her, the web site interaction is much more fluid and dynamic. The
next diagram shows a more detailed description of this idea at work.

The following diagram was taken from an article on the Sun Developer Network named
Asynchronous JavaScript Technology and XML (Ajax) With the Java Platform. It shows a
good representation of how Ajax technology works.




                                                                                            6
                                                                                     7/8/2007




        Figure 2 – Courtesy of Sun Developer Network (Murray, Greg, 2006)




“The following items represent the setups of an Ajax interaction as they appear in Figure 1 .

   1) A client event occurs.
   2) An XMLHttpRequest object is created and configured.
   3) The XMLHttpRequest object makes a call.
   4) The request is processed by the ValidateServlet.
   5) The ValidateServlet returns an XML document containing the result.
   6) The XMLHttpRequest object calls the callback() function and processes the
      result.
   7) The HTML DOM is updated.” (Murray, Greg, 2006)

This asynchronous communication between the client and the server is not unprecedented
within a browser. Java applets, ActiveX objects, and Flash players have all performed
similar feats. Java applets have never taken off as often expected (for whatever reason),
ActiveX has known security issues which make them unsuitable for many sites, and Flash
has a reputation for glossy eye candy over content (however deserved or undeserved). There
may be other technologies as well. Ajax, however, has exploded in popularity over the last
few years and appears to be the path the internet community has decided to follow. As such,
its suitability and usability for the task should be explored, evaluated, and understood.




Conclusion

When work was started on this paper, I, like many others, did not have any real idea of what
AJAX really was. I had begun hearing the term over the last couple of years and thought it



                                                                                            7
                                                                                      7/8/2007


was a new programming language or a perhaps a new paradigm of some sort. When I
discovered it was basically a buzz word created to help a development firm sell more
products more easily, I was a bit disappointed.

However, as I begin to learn more about what the term AJAX actually involved, I found
myself becoming more and more interested. I had discovered it to be a term to describe
various technologies working together to achieve a goal but how did that occur and what was
the goal? Was it something I needed to know or was it just smoke and mirrors? Did it
actually do anything for the developer?

My research led me to some interesting conclusions. AJAX was, without a doubt, a very
clever marketing tool by a very clever business man. However, it was also something all web
developers should really should embrace and understand. Though Jesse James Garret coined
the term to help sell his product he also coined the term to explain his product approach.

Clients might come in with preconceived notions of what technology the solution to their
particular problem would involve. Many were familiar with Macromedia‟s Flash technology
and liked the rich user experience of some of the sites created with this tool. Garrett knew,
though, that the same tool was not always the best tool for every different job. Often, some of
the less „flashy‟ technologies could be used in better ways to achieve the desired results.
These results were so much more responsive than most other web sites that clients wanted to
know what new technology he had come up with to work this magic. He eventually came up
with the term AJAX as a cool sounding acronym for the core components often used with
these sites.

But then something funny happened. The term caught on and, more importantly, the idea
behind the term caught on. By using well known technology such as JavaScript but
complementing it with the asynchronous communications provided by the XMLHttpRequest
object, web sites could be developed that were simple enough for the common web developer
to create and yet could be made responsive to the end user to such a degree that the
comparisons to desktop applications were not completely unfair.

The term AJAX may be artificial but the idea behind it and the actual results that come from
following that idea is anything but artificial. A real improvement in user interaction on web
sites is being made using these combined technologies and is something every web developer
should become familiar with. And having a shorter and easier to remember name such as
AJAX to use instead of having to refer to it as being something like „JavaScript and JSON
and HTML and CSS and the XMLHttpRequest object‟ seems like a good thing to me. Wish I
had thought of it first!




                                                                                             8
                                                                                      7/8/2007




BIBLIOGRAPHY
Ajax (programming). (2007, June 29). Retrieved June 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/Ajax_(programming)

Ajax Tutorial. (2007, June). (W3Schools) Retrieved June 26, 2007, from W3Schools.com:
http://www.w3schools.com/ajax/default.asp

Chess, B., O'Neil, Y., & West, J. (2007, March 12). JavaScript Hijacking. Retrieved June
2007, from Fortify Software:
http://www.fortifysoftware.com/servlet/downloads/public/JavaScript_Hijacking.pdf

Code Injection. (2007, June 14). Retrieved June 27, 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/Code_injection

Crane, D., Pascarello, E., & James, D. (2006). Ajax in Action. Greenwich, CT: Manning
Publications Co.

Cross Site Scripting. (2007, June 26). Retrieved June 26, 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/XSS

CSS. (2007, July 8). Retrieved July 8, 2007, from wikipedia.com:
http://en.wikipedia.org/wiki/Cascading_Style_Sheets

DOM. (2005, January 19). Retrieved July 8, 2007, from w3.org: http://www.w3.org/DOM

Garrett, James. (2005, Febuary 18). Ajax: A New Approach to Web Applications. Retrieved
June 25, 2007, from Adaptive Path:
http://www.adaptivepath.com/publications/essays/archives/000385.php

Hayes, D. (2006). Teach yourself HTML in 10 Minutes (Fourth Ed. ed.). Indianapolis: Sams
Publishing.

Heilmann, Chris. (2006). From DHTML to DOM scripting. Retrieved June 28, 2007, from
icant.co.uk: http://icant.co.uk/articles/from-dhtml-to-dom/from-dhtml-to-dom-scripting.html

HTML 4.01 Specification. (1999, December 29). Retrieved July 1, 2007, from W3C
Reccomendations: http://www.w3.org/TR/html4/index/list.html

JSON. (2007, June 29). Retrieved June 29, 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/JSON

Keith, J. (2007). Bulletproof Ajax. Berkeley: New Riders.

Markup Language. (2007, June 26). Retrieved July 7, 2007, from wikipedia.com:
http://en.wikipedia.org/wiki/Markup_language#XHTML




                                                                                              9
                                                                                     7/8/2007


Murray, Greg. (2006, October). Asynchronous JavaScript Technology and XML (Ajax) With
the Java Platform. Retrieved June 26, 2007, from Sun Developer Network:
http://java.sun.com/developer/technicalArticles/J2EE/AJAX/

Negrino, T., & Smith, D. (2004). Javascript for the World Wide Web (5th ed.). Berkeley:
Peachpit Press.

Petreley, N. (2007, May). Ajax Simplified. Linux Journal , 2007 (157). ACM Portal 28 June
2007 <http://portal.acm.org>

Remote Scripting. (2007, June 25). Retrieved June 25, 2007, from Wikipaedia:
http://en.wikipedia.org/wiki/Remote_Scripting

Rich Internet Application. (2007, June 29). Retrieved June 30, 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/Rich_Internet_application

Stamey, J., & Richardson, T. (2006). Middleware development with AJAX. Journal of
Computing Sciences in Colleges , 22 (2). ACM Portal. 4 July 2007 <http://portal.acm.org>

XML. (2007, June 28). Retrieved June 29, 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/XML

XMLHttpRequest. (2007, June 8). Retrieved June 28, 2007, from Wikipedia.org:
http://en.wikipedia.org/wiki/XMLHTTPRequest




                                                                                           10
                                                                                     7/8/2007




EXAMPLE CODE APPENDIX

All of the code in this section is taken from
http://www.javapassion.com/handsonlabs/ajaxexamples/

Please see the above url to download the zip file containing this code (and more). You can
also see www.javapassion.com/ajaxcodecamp for a free online course for developing ajax web
applications.

The code below is meant to show simple examples. Please see the source site for fuller details
and explanations.




Using Hidden Frames

Iframe.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <title>Example of remote scripting in an IFRAME</title>
  </head>
  <script type="text/javascript">
    function handleResponse() {
       alert('this function is called from server.html');
    }
  </script>
  <body>
  <h1>Remote Scripting with an IFRAME</h1>

  <iframe id="beforexhr"
  name="beforexhr"
  style="width:0px; height:0px; border: 0px" /*NOTE size is 0 */
  src="blank.html"></iframe>

  <a href="server.html" target="beforexhr">call the server</a>

  </body>
</html>


Server.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>



                                                                                           11
                                                                                    7/8/2007


 <head>
  <title>the server</title>
 </head>
 <script type="text/javascript">
  window.parent.handleResponse();
 </script>
 <body>
 </body>
</html>




Ajax using the XMLHttpRequest object
 Note that a different call is made for the XHR object depending upon the browser being
used but that once the object is created, no further browser dependant code is required.
Please see documentation or your instructer for further details on calling and using the
XMLHttpRequest object.


Simplereqest.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple XMLHttpRequest</title>

<script type="text/javascript">
var xmlHttp;

/* depends on the browser as to which call to use to create an XHR object */
function createXMLHttpRequest() {
   if (window.ActiveXObject) {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   else if (window.XMLHttpRequest) {
       xmlHttp = new XMLHttpRequest();
   }
}

function startRequest() {
  createXMLHttpRequest();
  xmlHttp.onreadystatechange = handleStateChange;
  xmlHttp.open("GET", "simpleResponse.xml", true);
  xmlHttp.send(null);
}

function handleStateChange() {
  if(xmlHttp.readyState == 4) {
     if(xmlHttp.status == 200) {
        alert("The server replied with: " + xmlHttp.responseText);
     }
  }



                                                                                           12
                                                                     7/8/2007


}
</script>
</head>

<body>
  <form action="#">
     <input type="button" value="Start Basic Asynchronous Request"
onclick="startRequest();"/>
  </form>
</body>
</html>


Simpleresponse.xml
Hello from the server!




                                                                          13

				
DOCUMENT INFO