Ajax Libraries


New Ajax libraries have been appearing almost daily since the term was coined. Most are targeted at one of the main Web development frameworks (JSP, ASP.NET, or PHP), but many others work well with any platform or even simple HTML pages. The libraries themselves range from simple libraries that make communication between client and server easier to libraries of widgets that use JavaScript to support editing. The benefit of using one of these libraries is that it can reduce the amount of code you must write to add Ajax support to your applications.

image from book
Mashups

With the number of services growing by the week, many developers are finding that communicating with one service just isn't enough. They are beginning to combine the data and features of multiple services, creating new services: for example, looking up store locations via a geocoding service and then plotting them on a map. These combination services have become known as mashups. Notice that I use mashup (without a hyphen), whereas a similar trend of combining music from multiple artists to create a new song is usually termed mash-up. Many authors use a single term for both or interchange the two words, however. Still, try to use the correct word the next time you're discussing your latest efforts at a cocktail party. With so many services providing online data or APIs, the number of potential mashups is rapidly becoming unlimited. The Web site Programmable Web (http://www.programmableweb.com) is a great resource to find useful services, as well as to locate known and potential combinations.

image from book

Some of the more notable Ajax libraries include the following: (Note, this list is hardly comprehensive. Dozens of other Ajax libraries are out there for all platforms, with more appearing every week)

  • q Microsoft AJAX Library, ASP.NET 2.0 AJAX Extensions, and the ASP.NET AJAX Control Toolkit-A collection of ASP.NET Ajax tools from Microsoft, formerly known as the "Atlas" project. This library works well with Internet Explorer, Firefox, and Safari. Although the extensions and control library are intended for use with Microsoft's ASP.NET, the core AJAX library can be used with other frameworks as well. Microsoft has demonstrated how it works with PHP pages.

  • q Prototype-Not an Ajax library per se, but a very useful tool for any JavaScript work. Prototype makes creating cross-browser JavaScript easier, and it adds a number of methods for doing common code procedures. Many other libraries, such as Script.aculo.us and moo, are written on top of the functionality provided by Prototype.

  • q Script.aculo.us-Not a standalone library, Script.aculo.us works with Prototype to create a number of common user interface Ajax functions. It is built into Ruby on Rails, and provides much of the Ajax functionality of that framework. Although it is part of Ruby on Rails, it works well with any Web application framework or even with simple HTML pages. In addition, the functionality it provides works cross-browser.

  • q AjaxPro-This is an Ajax library that targets Microsoft's ASP.NET framework, written by Michael Schwarz, and available in open source or commercial versions. It provides a quick method of adding Ajax support to Web applications. It works with ASP.NET 1.1 as well as 2.0.

  • q Echo2-A library of Ajax-enabled controls to add to Java-based Web applications. Works well across all common browsers.

  • q Symfony-A PHP5-based Ajax framework. Works well cross-browser. In addition to Ajax, it also includes support for templating and other Web application functionality.

Although a direct comparison of Ajax libraries is impractical and unfair because each developer's needs for platform and functionality vary, it is worth looking at how these libraries can be used to add common Ajax methods to your Web pages.

Using the Microsoft AJAX Library to Add Ajax Functionality

Microsoft AJAX is a set of technologies that extend ASP.NET 2.0 to add Ajax functionality. In addition to the library, Microsoft provides the AJAX Extensions that extends the HTML elements emitted by ASP.NET and the AJAX Control Toolkit that adds Ajax support to specific controls.

At the core of the Microsoft ASP.NET AJAX Extensions is the ScriptManager control. This outputs the appropriate JavaScript to the client, and provides cross-browser support. In addition, a number of additional controls, such as the UpdatePanel, are available.

Figure 14-7 shows an example of using Microsoft AJAX to create a simple RSS reader. When the drop-down list is changed, the list box is populated with the items from the selected RSS feed. Selecting items from the list causes the contents of the RSS item to be displayed on the right-hand side of the form. Because of the use of Ajax, the updates do not require any postbacks.

image from book
Figure 14-7

Listing 14-12 shows the source code for the RSS reader application. It uses the AJAX Extensions, and the RSSToolkit library written by Dmitry Robson of the ASP.NET team (see Resources).

Listing 14-12: The RSS Reader with the Microsoft AJAX Extensions

image from book
      <%@ Page Language="C#" %>      <%@ Register Assembly="RssToolkit" Namespace="RssToolkit" TagPrefix="rss" %>      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">      <script runat="server">          protected void FeedList_SelectedIndexChanged(object sender, EventArgs e) {              this.RssData.Url = this.FeedList.SelectedValue;              this.PostList.DataBind();          }          protected void PostList_SelectedIndexChanged(object sender, EventArgs e) {              this.RssData.Url = this.FeedList.SelectedValue;              this.ItemBody.Text =      this.RssData.Channel.Items[this.PostList.SelectedIndex].Attributes["description"];          }      </script>      <html xmlns="http://www.w3.org/1999/xhtml">      <head runat="server">          <title>Simple RSS Reader using Microsoft ASP.NET 2.0 AJAX Extensions</title>          <link href="styles.css" rel="stylesheet" type="text/css" />      </head>       <body>          <h1>Simple RSS Reader using Microsoft ASP.NET 2.0 AJAX Extensions</h1>          <form  runat="server">          <asp:ScriptManager  runat="server" EnablePartialRendering="true" />              <div>                  <asp:DropDownList runat="server"                      OnSelectedIndexChanged="FeedList_SelectedIndexChanged"                     Width="380px" AutoPostBack="true" EnableViewState="false">                     <asp:ListItem Text="Select a feed from the list" Value="" />                     <asp:ListItem Text="MSDN: XML"                       Value="http://msdn.microsoft.com/xml/rss.xml" />                     <asp:ListItem Text="'Atlas' Forum"                       Value="http://forums.asp.net/rss.aspx?ForumID=1007&amp;Mode=0" />                  </asp:DropDownList><br />                  <div >                     <asp:UpdatePanel runat="server" >                         <ContentTemplate>                             <asp:ListBox runat="server"                                 DataSource DataTextField="title"                                AutoPostBack="true"                                OnSelectedIndexChanged="PostList_SelectedIndexChanged"                                Rows="8"                                Css Width="274px"                                EnableViewState="false">                             </asp:ListBox>                         </ContentTemplate>                         <Triggers>                         <asp:AsyncPostBackTrigger Control                            EventName="SelectedIndexChanged" />                         </Triggers>                     </asp:UpdatePanel>                  </div>                  <div >                     <asp:UpdatePanel runat="server"                                     UpdateMode="Conditional"                                     >                         <ContentTemplate>                             <asp:Label  runat="server" />                         </ContentTemplate>                         <Triggers>                             <asp:AsyncPostBackTrigger Control                               EventName="SelectedIndexChanged" />                         </Triggers>                     </asp:UpdatePanel>                     <br />                     <br />                     <rss:RssDataSource  runat="server"                       Url="http://msdn.microsoft.com/rss.xml" />                  </div>              </div>           </form>      </body>      </html> 
image from book

The first step in using the AJAX Extensions is to load the ScriptManager control. This must be included within a control that includes the runat=“server” attribute. At runtime, this renders the appropriate JavaScript block to the client. With Internet Explorer, the code generated becomes:

      <script src="/books/2/381/1/html/2//AtlasReader/WebResource.axd?d=AUY39WO      iwTRIogu9AIMyv6Z5UsRE7EaRGPSTsch00K6Lyz2EON7S15vqL-      bgMC0KchPDT06BtbeFjyRdgUFdpkB6kgBIS3V36a7l7XfDiYLz-      EYY1MiTpqdR4XfUdtZYO0L6toHqkLPPJbUJy038yHwt9ninEaeJ4      FkHeGh3sdKA1&amp;t=632980743289843750" type="text/javascript">      </script> 

The Web resource actually points to about 11K lines of JavaScript code used by the rest of the framework. The EnablePartialRendering property means that only those sections of the page that have changed will be updated. This ensures that flickering is kept to a minimum.

Listing 14-13 contains the stylesheet used for the sample. The two selectors .leftContent and .rightContent cause the two sections to appear side by side.

Listing 14-13: Styles.css

image from book
      body {          font-family:Verdana,Arial, Sans-Serif;          font-size:0.8em;      }      .leftContent      {          float:left;          width: 250px;          padding-right: 30px;          border-right: solid 1px black;      }      .rightContent      {          padding-left: 30px;          margin: 5px 5px 5px 5px;      } 
image from book

The black box of the AJAX Extensions is the UpdatePanel. This control is used as a marker by the attached JavaScript code (that is, it does not produce any HTML output in itself). It identifies the controls that will be updated dynamically and the events that trigger the updates. In the preceding code, there are two UpdatePanels. One updates the Listbox that is populated with the post titles, and the other updates the content of each post item. The Triggers section of the control identifies the events that cause the contained controls to be updated. The code listed is actually executed on the server-side via Ajax, and the results are rendered to the page. The end result is a better experience for your clients, with less flicker and more feedback.

Using Prototype to Add Ajax Functionality

Prototype is a popular library, created by Sam Stephenson, which contains not only Ajax functionality but also a number of shortcuts for general JavaScript programming. Although it is not as large or full-featured as some of the other libraries, it has so many helpful shortcuts that many other libraries (such as Script.aculo.us that follows) are built on top of Prototype.

Listing 14-14 shows the client-side code for the contact lookup application created earlier. It has been modified to use Prototype and shows some of the added functionality of this library.

Listing 14-14: Client-side code using Prototype

image from book
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">      <html xmlns="http://www.w3.org/1999/xhtml" >      <head>          <title>Ajax Contact Lookup</title>          <script type="text/javascript" src="/books/2/381/1/html/2/scripts/prototype.js"></script>      <script language="javascript" type="text/javascript">      <!--          function getContacts() {              if("" != $F("q")) {                  var url="customerlookup.ashx";                  var parms = "q=" + $F("q");                  var target="contactList";                  var ajax = new Ajax.Updater(target,                                           url,                                           {method: "get",                                            parameters: parms,                                            onComplete: updateContent,                                            onFailure: reportError                                           });              } else {                  $("contactList").innerText = "";              }          }          function reportError(request) {              $F("contactList") = request.statusText;          }          function updateContent(req) {              var resp = req.responseXML;              var result = "";              var node = resp.documentElement.firstChild;              var nodes = resp.getElementsByTagName('customer');              for(i=0;i<nodes.length;i++) {                  result += dumpRow(nodes[i]);              }              $("contactList").innerHTML = result;          }          function dumpRow(row) {               var child = row.firstChild;              var result = "";              result += "<b>" + getValue(child) + "</b>&nbsp;";              child = child.nextSibling;              result += "(" + getValue(child) + "):&nbsp;";              child = child.nextSibling;              result += getValue(child);              result += "<br />";              return result;          }          function getValue(node) {              return Try.these(                  function() {return node.firstChild.nodeValue;},                   function() {return node.text;}                 );          }      // -->      </script>      </head>      <body>      <form>          Enter the first few letters of a company or contact:          <input  type="text" onkeyup="getContacts();"/><br />          <div ></div>      </form>      </body>      </html> 
image from book

The first step in using Prototype is to include the library on the page. You can download Prototype from http://www.prototype.conio.net. The current version (as of this writing) is 1.4.0.

One of the most common tasks developers face when building JavaScript applications is accessing the elements on a page, particularly form fields. Prototype includes two handy shorthand functions for returning this data: $(name) returns the element on the page, whereas $F(name) returns the value of the item. Although not earth-shattering in complexity, these two functions can save a lot of typing. In addition to these two functions, two others not shown include $H(object) for creating hashtables, and $A(object) for creating arrays.

In addition to the JavaScript shortcuts, Prototype also includes Ajax functionality in the form of three main classes:

  • q Ajax.Request-used to make individual requests to server-side code. This object wraps the XMLHttpRequest object, and makes it easier to add simple requests that work cross-browser.

  • q Ajax.Updater-used to update a region of the Web page based on server-side code. This object extends the Ajax.Request object to automatically change the contents of a named region of the page based on the returned data.

  • q Ajax.PeriodicalUpdater-used to update a region of the Web page based on server-side code at regular intervals. This object extends the Ajax.Updater, adding timer functionality so that the update happens as the timer fires.

Prototype alone may be enough to help you with your Ajax applications. Alternatively, one of the libraries that use Prototype as a starting point could be just what you need to make your Web applications more dynamic.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net