HTML Message - Ajax Patterns

HTML Message

From Ajax Patterns

Evidence: 3/3

Tags: AHAH Direct Display HTML InnerHTML Message Precise ServerSide Visual


Contents

In A Blink

Diagam Server talks (balloon) HTML.

  • Browser: "How does the account balance look?"
  • Server: "<pre><div><h2>Account Balance</h2> ... </div></pre>"


Technical jorge

Dave's identified the need for a credit history service, providing a list of transactions. Javascript resources are limited, so the entire HTML is created server-side, and the browser application only has to morph a DOM element with the entire HTML response.


Problem

What format should be used for server responses?


Forces

  • The browser display needs to be dynamic in Ajaxian applications.
  • The display changes by altering the DOM, and HTML is often used to specify the new value.
  • The nature of the change is often complex and needs to be determined server-side.


Solution

Have the server generate HTML snippets to be displayed in the browser. In this approach to Browser-Server Dialogue, the server-side service outputs some HTML. The HTML is picked up by the XMLHttpRequest callback function and an element morphed by setting its innerHTML property to the response HTML. In general, the server-side is application-specific, because the HTML response is closely tied to the application's display style.

The XMLHttpRequest allows callers to retrieve responses as either XML or plain-text. With HTML, it's usually easiest to retrieve it as a plain-text string. If the HTML is a pure XHTML document, XML is also an option, but usually that's not the case because there' no need for a header section. The entire response can be as simple as "You Win!". That's not an XHTML document because there's no <xml> tag, nor HTML header and body sections.

HTML Responses should be used with caution because they couple server-side services with browser display. That means it's difficult to develop the tiers in parallel. In maintenance, if you change the display by altering its initial HTML or any Javascript manipulation, you often need to change the HTML-generating service too. There's also a risk on the server-side that you might be coupling business logic with HTML generation. So when might HTML Responses be appropriate?

  • Server-Side Code Generation: One case where HTML Messages make some sense is with Server-Side Code Generation, where the server builds all the browser-side code for you. There are strengths and weaknesses of such frameworks, and if you decide to use one, then browser-server coupling is not really an issue because all maintained code is server-side anyway. A server-side code generation could use either Semantic Responses or HTML Responses, and the decision wouldn't have any impact on maintainability.
  • Legacy Code: Most legacy applications will use the conventional approach of publishing pages from the server. They therefore already have all the HTML generation present in the server-side environment, so if you're Ajaxifying a legacy application, a quick migration path is to retain the server-side HTML generation where possible.
  • Complex HTML: In the rare case that your HTML or Javascript is particularly complex, you might prefer to generate it all on the server-side, where development and debugging is sometimes easier.
  • Performance: Sometimes, there's some duplication of effort between browser and server. For instance, the server traverses a data structure to change some properties, and the browser re-traverses it for display. For a potential performance gain the browser loop could be "collapsed" into the server loop, allowing the server to output the entire block of HTML.
  • Server-Centric Attitude: Realistically, most usage of HTML Responses comes down to a server-centric attitude. If you don't have enough Javascript experience, or you're concerned about keeping as much logic as possible in the one language and environment, or you need to support legacy browsers, then HTML Messages may be more appropriate.

Typically, HTML messages rely on a block-level element existing in the DOM, often a div or form. The HTML message will contain a specification for the entire contents of the element. Some of the XMLHttpRequest wrapper libraries, such as Sack, support HTML messages by letting the caller specify a DOM element as the callback destination, instead of the usual callback function. When the response returns, the DOM element is automatically morphed with the service's response.


Decisions

At what level of granularity will the HTML apply?

In the extreme, the service could generate HTML for the entire document, making it similar to a conventional page refresh. In practice, you'll usually want to limit the HTML's level of granularity to well-defined, distinct, page elements. For example:

  • An account status.
  • A form.
  • A menu.

How much style will be contained in the message?

You'll need to decide how much style is contained in the message. An HTML Message already ties the server to the browser somewhat, but style directives will tie it further to the server. In general, it's good practice to just include class names and id's so that the browser application can influence the style, usually with a standard CSS stylesheet. If you do this, you'll need to ensure the names are unique and you'll need to decide on exactly which elements need to be given id and class declarations.


Real-World Examples

Rapha

Rapha is an E-Commerce website for cycling gear. The shopping cart is Ajaxian, requiring no page refresh to update. Each time an item is purchased, the HTML for the shopping cart is retrieved. For example:

  <div id="basket">
  <h3>Your basket:</h3>
  <ul>
  <li>Small Softshell Jacket x 2</li>
  </ul>
  <p><a href="/basket/">Edit selection</a> | <a href="/checkout/">Go to checkout</a></p>
  </div>

Digg Spy

Digg Spy shows recent news item submissions and is updated every few seconds. The XMLHttpRequest Call accesses a static URL containing the last 10 submissions, and integrates them into the page. The HTML looks like this:

  <head>
  </head>

  <body>

    <div class="news-body" id="main64115">
      <h3 id="title">
        <a href="http://digg.com/movies/How_LEGOs_Are_Made_"> How LEGOs Are Made! </a>
      </h3>
      <p class="news-submitted">
        <a href="/users/Akshun"><img src="/img/user-small/user-default.png" alt="Akshun" height="16" width="16"> </a>
      submitted by <a href="/users/Akshun"> Akshun </a> 14 hours 22 minutes ago 
        (<a href="http://www.popandco.com/archive/moab/" class="simple tight" title="How LEGOs Are Made!"> ... </a>) </p>
    <p> </p>
    </div>

    <div class="news-body" id="main64550">
    ...

  </body>

Amazon Zuggest

Francis Shanahan's Amazon Zuggest provides a Live Search: results are shown as you type. The server responds by providing the entire HTML for each result, for example:

  <table>
    <tr><td valign=top width='20%'><b>Vempire Or Dark Faerytales in Phallustei</b><br>
    <a href='http://www.amazon.com/exec/obidos/redirect?tag=francshanacom-20%26link_code=sp1%26camp=2025%26creative=165953%26path=http://www.amazon.com/gp/redirect.html%253fASIN=B0000525ZY%2526tag=francshanacom-20%2526lcode=sp1%2526cID=2025%2526ccmID=165953%2526location=/o/ASIN/B0000525ZY%25253FSubscriptionId=16KBB0XN5XP4WSNNVKG2' target=_blank>Click to View</a><br>
    [Music]<br>List Price<span class='lp'>$23.99</span><br>
    <span class='lnp'>1 NEW from $14.99[$13.50 used]</span>
    ...
  </td></tr><table>

TalkDigger

TalkDigger is a webfeed meta-search. You enter a query and it fires off parallel queries to different search engines (an example of Multi-Page Download. Each result is returned as an HTML table to be added to the page.


Code Examples

Digg Spy

Digg Spy responds with the full HTML to be displayed as well as some meta-content at the end. The results are fetched periodically - filldigs() is triggered by the recurring lastdigs(). filldigs() executes an XMLHttpRequest Call, extracts the HTML from the full response, and morphs the results panel using its innerHTML property.

 function startlastdigs() {
   window.setInterval("lastdigs()",15000);
 }
 function filldigs() {
   ...
   s.open("GET",url2,true);
   s.onreadystatechange=function() {
         if (s.readyState == 4) {
       ...
       b = responsestring2.split(split);
       ...
       document.getElementById('diggspy').innerHTML = b[0];
       ...
     }
   }
   ...
 }


Alternatives

Semantic Response

Semantic Response involves sending raw data as opposed to concrete display information. When the browser receives a Semantic Response, it can render it or use it in some other way, such as retaining some information. Semantic Messages can also be uploaded from the browser to the server, whereas the browser is unlikely to upload an HTML message.


Related Patterns


Visual Metaphor

Sending an HTML message is like sending a photograph - there's a lot of visual detail, while specific details (such as location and subjects) must be inferred.


Want to Know More?