AJAX

One of the major concerns of Information Technology in the present historical moment is making the Web and web applications as efficient as possible. This insures a business competitive edge in this era where operating systems and applications are increasingly accessed and/or stored on the Internet. Web applications that can function on a variety of platforms or in a variety of contexts have been difficult to attain. Third-party protocols like Flash or Java’s “applets” have tried to bring more dynamism and user-friendly interactivity to web applications.

Other limitations of using web applications are the frustration and workflow interruptions that come from page-loading delays. However, the technologies encompassed in Ajax (Asynchronous JavaScript and XML) try to enable web applications so they can function quickly and efficiently in a variety of contexts without this lag time.

This paper will describe the major technological components of Ajax. A brief outline of these will set the stage for understanding how they work together to enact Ajax methods that make web applications so much more competent and interoperable. Finally, this paper will discuss about jQuery. jQuery is an amazing JavaScript library that makes it easy to create wonderful web effects in just a few lines of code.

Introduction

Ajax (shorthand for asynchronous JavaScript and XML), is a group of interrelated web development techniques used on the client-side to create interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax has led to an increase in interactive animation on web pages and better quality of Web services due to the asynchronous mode. [2]

Brief History

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. It never had a name, but it can be called Dynamic XML. One of the most vivid examples 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 good 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 the function was available there, just waiting to be taken advantage of.

XMLHttpRequest allowed the JavaScript inside web pages to get more data. 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 the change. 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.

And the rest is future history.[3]

Main Building Block

Ajax is not a single technology. It is 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;
  • JavaScript binding everything together.

In other words, Ajax is an umbrella term for techniques used to make web applications look like desktop applications. Here is how it works: In the browser, code written in a scripting language—most frequently, JavaScript, which Chapter 2 is all about—watches what information the user wants, such as what term they’re searching for in Google Suggest. When, or even before, the user needs that information, the JavaScript code communicates with the web server behind the scenes to fetch that information without causing a page refresh in the browser.

That is, the way Ajax fetches data from the server is invisible to the user. The JavaScript code uses a special object built into the browser—an XMLHttpRequest object—to open a connection to the server and download data from the server. That data is often in XML format (the x in Ajax stands for XML), but it can be just plain text, as you’re going to see. When the data that the user needs has been downloaded behind the scenes, the JavaScript code uses that data to update the display in the browser. For example, in the earlier Google Suggest example, JavaScript was responsible for fetching, behind the scenes, the suggestions Google made and then displaying those suggestions in the drop-down list box after they were downloaded.

You’re not restricted to using drop-down list boxes with Ajax. You can do just about anything to display or report on the downloaded data, using JavaScript, because browsers support dynamic HTML, which means changes you make in the page are updated instantly in the browser without having to refresh the page. The text in the web page can be updated, for example, or get its size or color changed to bring the user’s attention to new text. You can chat with friends and have their comments appear in the web page in real time. You can even use Ajax, together with dynamic HTML, to download and display images corresponding to the information the user wants. For example, you might draw graphs of business stock performance on the server and then download and display them using Ajax and dynamic HTML—all without a page refresh. That behavior looks very nice: the user can select the stocks they want to chart, and the graph on the page changes to match, all with the feel of a desktop, not Internet, application.

Arhitectures of Ajax

The key to client/server communication in Ajax is to use the JavaScript XMLHttpRequest object. This object is supported by most browsers, including Windows® Internet Explorer 5.0 and higher, Safari 1.2, Mozilla Firefox, Opera 8 and higher, and Netscape 7. To understand the difference between traditional client/server communication and Ajax-based client/server communication, here is an example. Traditionally, for the client browser to send content to the server for processing or storing in a database, it was usually used a POST action to send content from input fields collected on the client side to the server. The server processes this content using PHP (or any scripting language of your choice), reads or stores data using a database, and returns the results embedded within HTML code. The HTML is then processed by the browser and a new page is rendered for the end user to view. Figure 1 depicts this scenario.

Fig. 1. Classic Web Application Model (oriented at [7])

Using Ajax, the same process requires less time on the front end. The idea is to make users feel as though they never have to wait for a page to update. In fact, using Ajax, you can develop the entire Web application using a single HTML page, though I highly recommend you don't. Traditionally, if you want to send a form to the server, you set the action of the form and specify the action type as POST. With Ajax, you don't actually submit a form directly to the server. Instead, you call a JavaScript function that verifies and collects the values from your form and then sends the data to a server-side function using XMLHttpRequest.

Fig. 2. Ajax Web Application Model

The result is sent back at some point to the client, which then processes the result and updates the portions of the page that need updating. In this case, the page is not entirely refreshed. Therefore, less time is spent processing HTML. As a result, the performance is better. Figure 2 illustrates how the process is slightly different when using Ajax, producing an update to the page rather than a refresh of the entire page.[6]

jQuery

Ajax framework can help us to quickly develop web pages that can call web services and server pages through JavaScript without having to submit the current page. Recent Web-applications tend to use them to provide more interactivity and guarantee better functionality. There are hundreds of Ajax/JavaScript frameworks available. But we would just list some of them.

Here we would briefly discuss jQuery. jQuery is a Javascript library that takes this motto to heart: Writing JavaScript code should be fun. jQuery achieves this goal by taking common, repetitive, tasks, stripping out all the unnecessary markup, and leaving them short, smart and understandable.

It began as a labor of love back in 2005 by John Resig, a JavaScript wunderkind who now works for the Mozilla Corporation. Inspired by pioneers in the field such as Dean Edwards and Simon Willison, Resig put together a set of functions to make it easy to programmatically find elements on a web page and assign behaviors to them. By the time he first publicly announced his project in January 2006, he had added DOM modification and basic animations. He gave it the name jQuery to emphasize the central role of finding, or “querying,” parts of a web page and acting on them with JavaScript. In the few short years since then, jQuery has grown in its feature set, improved in its performance, and gained widespread adoption by some of the most popular sites on the Internet. While Resig remains the lead developer of the project, jQuery has blossomed, in true open-source fashion, to the point where it now boasts a core team of top-notch JavaScript developers, as well as a vibrant community of thousands of developers.

The jQuery JavaScript Library can enhance the websites regardless of the background. It provides a wide range of features, an easy-to-learn syntax, and robust cross-platform compatibility in a single compact file. What's more, hundreds of plug-ins has been developed to extend jQuery's functionality, making it an essential tool for nearly every client-side scripting occasion.

Learning jQuery provides a gentle introduction to jQuery concepts, allowing adding interactions and animations to web pages. This book guides you past the pitfalls associated with AJAX, events, effects, and advanced JavaScript language features, and gives a brief reference to the jQuery library to return to again and again. Following are some of the architectures on the basis of deployment strategies. [5]

What jQuery does?

The jQuery library provides a general-purpose abstraction layer for common web scripting, and is therefore useful in almost every scripting situation. Its extensible nature means that we could never cover all possible uses and functions in a single book, as plugins are constantly being developed to add new abilities. The core features, though, address the following needs:

  • Access elements in a document. Without a JavaScript library, many lines of code must be written to traverse the Document Object Model (DOM) tree, and locate specific portions of an HTML document's structure. A robust and efficient selector mechanism is offered in jQuery for retrieving the exact piece of the document that is to be inspected or manipulated.
  • Modify the appearance of a web page. CSS offers a powerful method of influencing the way a document is rendered, but it falls short when web browsers do not all support the same standards. With jQuery, developers can bridge this gap, relying on the same standards support across all browsers. In addition, jQuery can change the classes or individual style properties applied to a portion of the document even after the page has been rendered.
  • Alter the content of a document. Not limited to mere cosmetic changes, jQuery can modify the content of a document itself with a few keystrokes. Text can be changed, images can be inserted or swapped, lists can be reordered, or the entire structure of the HTML can be rewritten and extended—all with a single easy-to-use Application Programming Interface (API).
  • Respond to a user's interaction. Even the most elaborate and powerful behaviors are not useful if we can't control when they take place. The jQuery library offers an elegant way to intercept a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers. At the same time, its event-handling API removes browser inconsistencies that often plague web developers.
  • Animate changes being made to a document. To effectively implement such interactive behaviors, a designer must also provide visual feedback to the user. The jQuery library facilitates this by providing an array of effects such as fades and wipes, as well as a toolkit for crafting new ones.
  • Retrieve information from a server without refreshing a page. This code pattern has become known as Asynchronous JavaScript and XML (AJAX), and assists web developers in crafting a responsive, feature-rich site. The jQuery library removes the browser-specific complexity from this process, allowing developers to focus on the server-end functionality.
  • Simplify common JavaScript tasks. In addition to all of the document-specific features of jQuery, the library provides enhancements to basic JavaScript constructs such as iteration and array manipulation.[5]

Why is jQuery better?

With the recent resurgence of interest in dynamic HTML comes a proliferation of JavaScript frameworks. Some are specialized, focusing on just one or two of the above tasks. Others attempt to catalog every possible behavior and animation, and serve these all up pre-packaged. To maintain the wide range of features outlined above while remaining compact, jQuery employs several strategies:

  • Leverage knowledge of CSS. By basing the mechanism for locating page elements on CSS selectors, jQuery inherits a terse yet legible way of expressing a document's structure. The jQuery library becomes an entry point for designers who want to add behaviors to their pages because a prerequisite for doing professional web development is knowledge of CSS syntax.
  • Support extensions. In order to avoid “feature creep”, jQuery relegates special-case uses to plugins. The method for creating new plugins is simple and well-documented, which has spurred the development of a wide variety of inventive and useful modules. Even most of the features in the basic jQuery download are internally realized through the plugin architecture, and can be removed if desired, yielding an even smaller library.
  • Abstract away browser quirks. An unfortunate reality of web development is that each browser has its own set of deviations from published standards. A significant portion of any web application can be relegated to handling features differently on each platform. While the ever-evolving browser landscape makes a perfectly browser-neutral code base impossible for some advanced features, jQuery adds an abstraction layer that normalizes the common tasks, reducing the size of code, and tremendously simplifying it.
  • Always work with sets. When jQuery is instructed to find all elements with the class collapsible and hide them, there is no need to loop through each returned element. Instead, methods such as .hide() are designed to automatically work on sets of objects instead of individual ones. This technique, called implicit iteration, means that many looping constructs become unnecessary, shortening code considerably.
  • Allow multiple actions in one line. To avoid overuse of temporary variables or wasteful repetition, jQuery employs a programming pattern called chaining for the majority of its methods. This means that the result of most operations on an object is the object itself, ready for the next action to be applied to it.

These strategies have kept the jQuery package slim—under 20 KB compressed—while at the same time providing techniques for keeping our custom code that uses the library compact, as well.

Licensed

Despite all of the efforts required to engineer such a flexible and robust system, the end product is free for all to use. This open-source project is dually licensed under the GNU Public License (appropriate for inclusion in many other open-source projects) and the MIT License (to facilitate use of jQuery within proprietary software).[5]

jQuery Example

The following example, found in the tutorials section on the jQuery website [8] will show an expandable collapsible menu placed on a side of a web page. We will use jQuery here to take a nicely formatted HTML and make it look fancier – what jQuery is all about. The menus will expand and contract as we choose one of them, like in the picture:

We should first start with a html definition of a blank page with the title “Definition List Demo”

 

<html>
<head>
	<title>Definition List Demo</title>
</head>
<body>
	...
</body>
</html>

The body of the HTML document is simple and contains the definition list with the main links as headers and the submenus:

 

<body>
<dl>
	<dt><a href="/">jQuery</a></dt>
	<dd>
	<ul>
		<li><a href="http://jquery.com/src/">Download</a></li>
		<li><a href="http://jquery.com/docs/">Documentation</a></li>
		<li><a href="http://jquery.com/blog/">Blog</a></li>
	</ul>
	</dd>
	<dt><a href="/discuss/">Community</a></dt>
	<dd>
	<ul>
		<li><a href="http://jquery.com/discuss/">Mailing List</a></li>
		<li><a href="http://jquery.com/tutorials/">Tutorials</a></li>
		<li><a href="http://jquery.com/demos/">Demos</a></li>
		<li><a href="http://jquery.com/plugins/">Plugins</a></li>
	</ul>
	</dd>
	<dt><a href="/dev/">Development</a></dt>
	<dd>
	<ul>
		<li><a href="http://jquery.com/src/">Source Code</a></li>
		<li><a href="http://jquery.com/dev/bugs/">Bug Tracking</a></li>
		<li><a href="http://jquery.com/dev/recent/">Recent Changes</a></li>
	</ul>
	</dd>
</dl>
</body>

We also add styles for the HTML tags, so the page looks nice:

 

<style>
	body { font-family: Arial; font-size: 16px; }
	dl { width: 300px; }
	dl,dd { margin: 0; }
	dt { background: #F60; font-size: 18px; padding: 5px; margin: 2px; }
	dt a { color: #FFF; }
	dd a { color: #000; }
	ul { list-style: none; padding: 5px; }
</style>

In order to use the jQuery library we need to include the jQuery JavaScript library:

 

<script src="jquery-1.3.2.js"></script>

The jQuery library script can be downloaded from http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.js

In order to run a code right when the page is loaded, usually it was being placed in the window.onload event, similar to this:

 

window.onload = function(){ alert("welcome"); }

Problematically, however, the JavaScript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:1)

 

 $(document).ready(function(){
   // Your code here
 });

In conclusion, the first we need to do with any jQuery code is to make sure it is contained in a $(document).ready event. This means that the document is ready to be browsed and manipulated before the code is executed.

We will start by hiding the definitions for all the items that are not the first one – namely, only the definition of the first item is visible, the others are hidden – with a code similar to:

 

$("dd:not(:first)").hide();

The next step is to make sure that when one of the links is clicked on, instead of following the link (as the menu headers are links to different web pages), the item definition goes visible with an accordion effect: the one currently visible will slide up and the one clicked on will expand slowly.

In order to make the click event do what we just described, we need to stop the event from doing what it normally should do: follow the link. So, for all the dt terms, we find the anchor inside of it and attach a click event. The function defined to respond for the click event should return false in order for the normal behavior to be prevented. This is accomplished with the following code:

 

$("dt a").click(function(){
	return false;
});

If you now open the page in a browser and try out the click, it will not work - no event will be triggered.

The next step is to define the animation we wish to have as a result of the click event. We accomplish this by finding all the visible definition blocks, slide them up slowly, and additionally slide down the item definition below the menu which has been clicked. Since we are positioned on the anchor item (pointed to with this in jQuery), we need to access its parent and slide down the next item, which is the definition:

 

$("dd:visible").slideUp("slow");
$(this).parent().next().slideDown("slow");

Putting the jQuery code together and adding it in the ready event of the document as we previously explained, we get the following:

 

$(document).ready(function(){
		$("dd:not(:first)").hide();
		$("dt a").click(function(){
			$("dd:visible").slideUp("slow");
			$(this).parent().next().slideDown("slow");
			return false;
		});
	});

The complete code listing of the web page added as a code example is listed below:

 

<html>
<head>
	<title>Definition List Demo</title>
	<script src="jquery-1.3.2.js"></script>
	<script>
	$(document).ready(function(){
		$("dd:not(:first)").hide();
		$("dt a").click(function(){
			$("dd:visible").slideUp("slow");
			$(this).parent().next().slideDown("slow");
			return false;
		});
	});
	</script>
	<style>
	body { font-family: Arial; font-size: 16px; }
	dl { width: 300px; }
	dl,dd { margin: 0; }
	dt { background: #F60; font-size: 18px; padding: 5px; margin: 2px; }
	dt a { color: #FFF; }
	dd a { color: #000; }
	ul { list-style: none; padding: 5px; }
	</style>
</head>
<body>
<dl>
	<dt><a href="/">jQuery</a></dt>
	<dd>
	<ul>
		<li><a href="http://jquery.com/src/">Download</a></li>
		<li><a href="http://jquery.com/docs/">Documentation</a></li>
		<li><a href="http://jquery.com/blog/">Blog</a></li>
	</ul>
	</dd>
	<dt><a href="/discuss/">Community</a></dt>
	<dd>
	<ul>
		<li><a href="http://jquery.com/discuss/">Mailing List</a></li>
		<li><a href="http://jquery.com/tutorials/">Tutorials</a></li>
		<li><a href="http://jquery.com/demos/">Demos</a></li>
		<li><a href="http://jquery.com/plugins/">Plugins</a></li>
	</ul>
	</dd>
	<dt><a href="/dev/">Development</a></dt>
	<dd>
	<ul>
		<li><a href="http://jquery.com/src/">Source Code</a></li>
		<li><a href="http://jquery.com/dev/bugs/">Bug Tracking</a></li>
		<li><a href="http://jquery.com/dev/recent/">Recent Changes</a></li>
	</ul>
	</dd>
</dl>
</body>
</html>

jquery_accordioneffect.zip

jQuery UI Widgets

Even if a programmer can use jQuery library to create the custom behavior that he wants on a webpage, there already exists a set of UI pluggins and widgets with a predefined behavior which can be embedded in a web page.

jQuery UI provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.

Demos, documentation, the possibility to create a custom theme and to download the source code can be found in the UI section on the jQuery web page: http://jqueryui.com/home.

jquery_uiwidgets.zip

Conclusion

Ajax has changed the web. There’s no doubt about that. It’s made the internet a happier place to be (well, when it’s used well) and has helped fuel the Web 2.0 movement to make it what it is today.

While every new technology should be greeted with a healthy amount of skepticism, there are clearly demonstrable, quantifiable advantages to using Ajax architecture in a web application. These cost savings originate primarily from time savings, but also from reductions in bandwidth requirements. A business can save between 500 and 2,800 man hours per year on a 10 step hypothetical process, saving roughly 4 seconds per step (between 30% and 70% reduction in labor costs). While the benefits of improved application architecture extend beyond mere time savings, when included in the decision making process, an ROI approach such as this can help make a solid business case for Ajax.

References

1) To embed this javascript code into a HTML-page, include it between script-tags: <script type=“text/javascript”>…</script>
Last modified: 2013/05/13 18:30
*