AJAX: A Fresh Look at Web Development

AJAX: A Fresh Look at Web Development

ouldn’t it be nice if you could turn your plain old Web pages into something more exciting? Isn’t it time to inject some life into your decade-old Web technologies? If you feel the need for the fresher, richer, and more interactive Web experience, get to know AJAX.

If you use Google Maps or the Gmail Web client you actually have experienced an AJAX-based solution already. AJAX, which stands for asynchronous JavaScript and XML, is a conglomerate technology that enables dynamic, asynchronous behavior on Web pages without the need for annoying browser page refreshes. Utilizing AJAX, users can interact with Web pages almost as they would with rich clients.

AJAX is a simple technology that all the major browsers already support. As you will see shortly, the only prerequisite for AJAX implementation is knowledge of JavaScript.

How AJAX Works

If you’ve used the Gmail Web client or Google Maps you probably noticed that you can scroll over the map or spell check the typed text, respectively, without page submits. AJAX, the technology behind this behavior, handles the requested operations in _JavaScript and asynchronously invokes the server-side operations that provide the desired results.

Introducing the XMLHttpRequest

At the core of AJAX technology is a JavaScript object: XMLHttpRequest. This object has been supplied through browser implementations?first through Internet Explorer, and then through Mozilla/Safari. At the time of writing this article, version 8 of the Opera browser supplied a compatible implementation. However, Opera has had a somewhat rocky history in terms of the stability of its XMLHttpRequest implementation.

AJAX in Action

In order to demonstrate AJAX, this tutorial implements a common portal scenario: e-mail message previewing. (Click here for the application source code.) Most Web portals allow portal users to preview the contents of their e-mail inboxes from the main page. In order to view the body text in their messages, however, users need to click on the individual messages?one by one, refreshing the page each time. This case study demonstrates how to practically accomplish richer Web client behavior, similar to what rich clients like Outlook Express and Mozilla Thunderbird provide, utilizing the existing Web technologies of AJAX.

It builds a portlet that provides not only access to the list of most recent messages but also previews of the messages themselves?all from the main page without needing to refresh.

In order to access message content, you need a server component that provides access to the messages. This demonstration utilizes a trivial servlet that will serve as a simulator, providing a comma-separated representation of the messages: from, subject, date, and message body:

@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {				if ( req.getParameter( "message_id" ).equals( "1" ) ){						resp.getWriter().println( "John Doe,Greetings,10-10-2005,Hi.I am doing good" );					}else if ( req.getParameter( "message_id" ).equals( "2" ) ){						resp.getWriter().println( "Joanna Doe,Hi,10-10-2005,Document is complete." );					}else if ( req.getParameter( "message_id" ).equals( "3" ) ){						resp.getWriter().println( "Joanna Doe,Hi,10-10-2005,Meeting is at 3." );			...		}else{						resp.getWriter().println( ",NA ,NA ,NA ,Nothing to display" );					}//end else	}//end service

Your portal will have a mail preview portal window/portlet with a simplistic inbox listing on the left side and the preview pane on the right side. As you mouse over the message on the left, the preview pane makes the server call and displays the message text?in real time?utilizing AJAX.

Step 1: Creating Web Mail Preview Portlet
 
Figure 1. Web Page That Simulates a Typical Web Mail Portlet

To begin, create the Web page that simulates the look and feel of a typical Web mail portlet and incorporates JavaScript onMouseOver events that trigger AJAX calls (see Figure 1).

In this case, “onMouseOver” events are attached to table fields (TD) that contain names of the e-mail senders. This choice of data fields and the triggering events for AJAX calls are strictly for illustrative purposes:

       
"inbox"> "previewTable"> "tableHeader"> "even"> "even"> ...
From Subject
"displayMessageBody(1)">John Doe Greetings
"displayMessageBody(2)">Joanna Doe Status of the report
"displayMessageBody(3)">Jim Doe Meeting is today
"preview"> "messageBody"class="message" type="textarea" READONLY value=""/>

Notice that the input field “messageBody” is the one that will be populated by the method displayMessageBody, which takes the message ID as a parameter. An AJAX call will use this parameter to request the message details from the server. (Complete source for this application is available for download. Please see resources)

Step 2: Making an AJAX Call

The key element of this implementation is an AJAX call. In the following code, notice how different browser implementations require different instantiation methods for the XMLHttpRequest object:

function getHTTPRequestObject() {  var xmlHttpRequest;  /*@cc_on  @if (@_jscript_version >= 5)    try {      xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");    } catch (exception1) {      try {        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");      } catch (exception2) {        xmlhttp = false;      }    }  @else  xmlhttpRequest = false;  @end @*/   if (!xmlHttpRequest && typeof XMLHttpRequest != 'undefined') {    try {      xmlHttpRequest = new XMLHttpRequest();    } catch (exception) {      xmlHttpRequest = false;    }  }  return xmlHttpRequest;}var httpRequester = getHTTPRequestObject(); // Create the xml http object on the page load

This code utilizes Internet Explorer annotations to instantiate an AJAX object. Other browsers executing this script will simply ignore the annotated sections of the getHTTPRequestObject() function. Keep in mind that your browser must support JavaScript 1.5 and above.

Step 3: Asynchronous Loading of the Content

This step implements the asynchronous invocation of the Web resources. The following code illustrates the exact steps required for the asynchronous loading of the Web resources from the JavaScript function:

var couldProcess = false;function displayMessageBody( messageID ) {  idToDisplay = messageID    if (!couldProcess && httpRequester) {    httpRequester.open("POST", serverSideURL + escape(messageID), true);    httpRequester.onreadystatechange = processResponse;    couldProcess = true;    httpRequester.send(null);	  }  }

The method displayMessageBody accepts the ID of the message to display. It specifies how the XMLHttpRequest object should access the URL by passing the following three parameters:

  • The method POST or GET
  • The URL, plus any escaped parameters (In this case, you pass only an ID. To specify multi-parameter URLs, use the standard URL query string notations and always escape.)
  • A Boolean flag indicating whether the call should be executed in an asynchronous fashion

The method also sets the content-processing method processResponse as a callback, which is invoked when the content from the URL loads.

Step 4: Processing the Results

The previously mentioned method processResponse is invoked as a callback. It takes the output from the XMLHttpRequest object, parses it, and assigns it to the page object(s):

function processResponse() {  if ( httpRequester.readyState == COMPLETE ) {//this is a locally declared constant, its                                                 // value is 4       if ( httpRequester.responseText.indexOf('invalid') == -1 ) {      	  var values = httpRequester.responseText.split(","); // parse the server response   	  document.getElementById('messageBody').value = values[3];//pick the fourth value                                                                    // and actual message       	           couldProcess = false;          }  }}

HttpRequester.readyState is an indicator that declares the completion of the URL code. It can take the following values:

  • 0 = uninitialized
  • 1 = loading
  • 2 = loaded
  • 3 = interactive
  • 4 = complete (This demo focuses on this state.)
  • Notice that the response is accessed as textual content. XMLHttpRequest can easily retrieve non-XML text, as well as XML content.

    If you needed to retrieve XML content, the line would read responseXML and you would access it as XML DOM object. This versatility of text formats is welcome news because XML could be overkill for simple data retrieval scenarios like the one described here.

    Step 5: Improving the Robustness of the AJAX Application

    Any extensive use of JavaScript inevitably raises concerns about the robustness and reliability of an application that heavily relies on this very relaxed and forgiving scripting language. With AJAX, the issue is even more complicated. AJAX makes remote calls, which introduce an additional dimension of complexity and the opportunity for errors?especially considering that built-in support for server-side error conditions is very limited.

    With all this in mind, here are some immediate error-prevention suggestions:

    • Make sure that your application can function in a bare bones mode, even without the AJAX.
    • Verify response codes from the AJAX calls before the further processing of the results.XMLHttpRequest API supports HTTP codes (200, 400, …). These can be accessed via the status property (along with the statusText property, which holds the message associated with the status of the response):
      if ( httpRequester.readyState == 4) {// if the status is 200 (OK) proceedif ( httpRequester.status == 200) {// ... process results ...} else {// ... handle or report error here ...}

    AJAX Implementation: An Art of Tradeoffs

    Many programmers consider JavaScript a sub-optimal programming solution because of its lacking debugging methods and its error-prone, weak-typed programming model. With this in mind, it is fair to say that AJAX is a solution of trade-offs. You trade the safety of the more robust languages like Java or C# for the presentational attractiveness and the innovative appeal of this JavaScript-based technology.

    Hopefully, the popularity of AJAX and the increasing use of JavaScript will prompt browser producers to further innovate the JavaScript objects and incorporate mechanisms that make JavaScript objects a bit more compatible, safer to use, and easier to debug.

    In the meantime, I see AJAX as an immediate candidate for the new generation of Internet portals and interactive applications. With AJAX, Internet news portals such as Yahoo, Google News, or MSN will allow users to access all areas of interest?including specific details?from the same portal page.

    The promise of rich clients that can be implemented by leveraging existing Web technologies and Internet infrastructure as-is is attractive. Interactive communication applications already have adopted AJAX?Google uses it for its ultra-popular Gmail e-mail client?and I expect this trend to continue.

    One advantage that software development teams will enjoy is this technology’s accessibility and flat learning curve. As previously mentioned, it is available on all modern browsers. Also, it does not require advanced programming skills like J2EE or .NET, yet it can produce impressive and effective results that will appeal to end users.

    Helpful Tools and Extensions

    As AJAX grows in popularity, helpful third-party extensions will continue to emerge?ones that make complex tasks such as debugging, cross-browser development, and XML processing easier. Some of the more prominent extensions that you may find helpful today are:

    • Greasemonkey
      Greasemonkey is a Firefox extension that enables installation of custom DHTML scripts. Some blog authors (see resources) have produced scripts that help trace and debug AJAX routines utilizing Greasemonkey features.
    • Sarrisa
      Sarrisa is a script library that automates and simplifies the most common XML operations (e.g., XML document loading from URL, instantiations, XPath, XSLT processing) with AJAX, as well as cross-browser implementations and testing.
    • Direct Web Remoting (DWR)
      DWR is an AJAX-based Java remoting library that enables asynchronous remote invocation of Java server code from the JavaScript routines.
    devx-admin

    devx-admin

    Share the Post:
    Clean Energy Adoption

    Inside Michigan’s Clean Energy Revolution

    Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

    Chips Act Revolution

    European Chips Act: What is it?

    In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

    Revolutionized Low-Code

    You Should Use Low-Code Platforms for Apps

    As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

    Global Layoffs

    Tech Layoffs Are Getting Worse Globally

    Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

    Clean Energy Adoption

    Inside Michigan’s Clean Energy Revolution

    Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

    Chips Act Revolution

    European Chips Act: What is it?

    In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

    Revolutionized Low-Code

    You Should Use Low-Code Platforms for Apps

    As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

    Cybersecurity Strategy

    Five Powerful Strategies to Bolster Your Cybersecurity

    In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

    Global Layoffs

    Tech Layoffs Are Getting Worse Globally

    Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

    Huawei Electric Dazzle

    Huawei Dazzles with Electric Vehicles and Wireless Earbuds

    During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

    Cybersecurity Banking Revolution

    Digital Banking Needs Cybersecurity

    The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

    FinTech Leadership

    Terry Clune’s Fintech Empire

    Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

    The Role Of AI Within A Web Design Agency?

    In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

    Generative AI Revolution

    Is Generative AI the Next Internet?

    The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

    Microsoft Laptop

    The New Surface Laptop Studio 2 Is Nuts

    The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

    5G Innovations

    GPU-Accelerated 5G in Japan

    NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

    AI Ethics

    AI Journalism: Balancing Integrity and Innovation

    An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

    Savings Extravaganza

    Big Deal Days Extravaganza

    The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

    Cisco Splunk Deal

    Cisco Splunk Deal Sparks Tech Acquisition Frenzy

    Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

    Iran Drone Expansion

    Iran’s Jet-Propelled Drone Reshapes Power Balance

    Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

    Solar Geoengineering

    Did the Overshoot Commission Shoot Down Geoengineering?

    The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

    Remote Learning

    Revolutionizing Remote Learning for Success

    School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

    Revolutionary SABERS Transforming

    SABERS Batteries Transforming Industries

    Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

    Build a Website

    How Much Does It Cost to Build a Website?

    Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

    Battery Investments

    Battery Startups Attract Billion-Dollar Investments

    In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

    Copilot Revolution

    Microsoft Copilot: A Suit of AI Features

    Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

    AI Girlfriend Craze

    AI Girlfriend Craze Threatens Relationships

    The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

    AIOps Innovations

    Senser is Changing AIOps

    Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions