Sample Code

Using AJAX to Dynamically Load Press Releases

We use a simple Perl script to dynamically list all of the Press Releases that our Press Flak creates for us. Essentially, the creation of Press Releases has been simplified to the point where our Press Flak edits the Press Release and drops it into the PR directory. That's all the manual intervention required. From there, any links to the new Press Release are built dynamically, on the fly.

We wanted to extend this model to display a squib about the latest press release, dynamically on our home page. Unfortunately, one of the great oversights in HTML is its inability to imbed simple text or HTML into a page. Certainly, this capability is provided via server-side includes or a scripting language such as PHP. However, we wanted to keep the home page simple, so that it could be dropped onto any Web server, regardless of whether server-side scripting (shtml) or PHP was available.

Using AJAX turned out to be a nearly-perfect way to achieve our goal.

How Press Releases Work

The Perl script that lists Press Releases reads a template file and looks for an insertion point within it. When it finds the insertion point, it enumerates all of the files that match the Press Release file pattern, sorts them in descending chronological order, and inserts a few lines for each one that look like this:

<p><a href="/Reference/Samp_AJAXTextLoading.html">
<i>Loading Press Releases With AJAX - Sample Code</i></a>
<br>How to load press releases, on the fly, into Web pages, using AJAX.

The actual information inserted into the list is read by the Perl script from the <title> tag and a meta-tag named "subject". Here is how the heading of the Press Release itself looks:

<title>Loading Press Releases With AJAX - Sample Code</title>
<meta name="subject" content="How to load press releases, on the fly, into Web pages, using AJAX.">

In order to be able to load the latest Press Release dynamically, the script was modified to accept a count such that only the number of list elements specified by the count (after sorting) would be output. By setting count to 1, only the latest Press Release would be output. You can see the results here.

AJAX Template

A simple template was created for use with AJAX to load the latest Press Release on the fly. It looked like this:

<p align=left style="margin-left: 20px;">
<html><head>
<title>Dynamic Press Releases</title>
</head><body>
$About/PR_$
</body></html>

As you can probably guess, the "$About/PR_$" line is the insertion point for the Press Release list.

AJAX Text Loader

Loading of the text generated by the AJAX template was done by a simple routine that looks like this:


function LoadText(TextObject, AJAXLoader)
{
var Container;                          // Container for text read
var AJAXObject = null;                  // AJAX load object

// We must be able to find the object that the caller wants us
// to use.  If not, we can't go on.
if (document.all && !document.getElementById)
  { Container = document.all[TextObject]; }
else { Container = document.getElementById(TextObject); }

if (!Container) return;

// Let's see if we can get hooked up with AJAX (Mozilla, Safari, ...).
if (window.XMLHttpRequest) { AJAXObject = new XMLHttpRequest(); }

// Microsoft.
else if (window.ActiveXObject)
  {
  try { AJAXObject = new ActiveXObject("Msxml2.XMLHTTP"); } 
  catch (except)
    {
    try { AJAXObject = new ActiveXObject("Microsoft.XMLHTTP"); } 
    catch (except) {}
    }
  }

// Here we go.
if (AJAXObject)
  {
  // Once we have some results, we'll process them here.
  AJAXObject.onreadystatechange = function()
    {
    var ReadyState, Status, Matches;

    // In the event of a comm error, accessing the state variable
    // in the AJAX object will throw an exception.
    try { ReadyState = AJAXObject.readyState; }
    catch(except) { ReadyState = 4; }

    // This routine can get invoked under several circumstances.
    // The only one we are interested in is if the readyState is
    // 4 (request complete).  Otherwise, we just return.
    if (ReadyState != 4) { return; }

    // Exceptions are possible for the status variable too.
    try { Status = AJAXObject.status; }
    catch(except) { Status = 503; }

    // If we were successful, its time to parse the response text.
    if (Status == 200)
      {
      var ParsedText;

      // Let's parse the response to get just the text.  Nothing
      // elaborate, just a regexp match (except for the JavaScript
      // boneheads decided that '.' shouldn't match newline).
      Matches = AJAXObject.responseText.match(
        /<body[^>]*>([\x00-\xFF]+)<\/body/im);

      // If we got a match, save the parsed text.  Incidentally,
      // the string function replace() is a piece of junk that
      // doesn't work.  Hence, the second call to match() to strip
      // blanks from the front/back.  Also, we must do it in two
      // steps, since /[\x00-\xFF]+/ will match the trailing blanks,
      // once it gets going in the first match().
      if (Matches)
        {
        ParsedText = Matches[1];
        Matches = ParsedText.match(/^\s+([\x00-\xFF]+)/m);
        if (Matches) { ParsedText = Matches[1]; }
        Matches = ParsedText.match(/([\x00-\xFF]+)\s+$/m);
        if (Matches) { ParsedText = Matches[1]; }

        // Set the object's text content to the parsed text.
        // The browser must support innerHTML so that any tags
        // will be parsed properly.
        if (typeof(Container.innerHTML) != 'undefined')
          { Container.innerHTML = ParsedText; }
        }
      }

    // That's all for Ray Nance.
    return;
    };

  // Invoke the AJAX loader URL.  Do it asynchronously.  What's
  // the benefit of doing it this way?  Well, at least the user's
  // browser isn't hung if something goes wrong.
  AJAXObject.open('GET', AJAXLoader, true);
  AJAXObject.send(null);
  return;
  }

// We're done.
return;
}

Invoking the AJAX Loader

All that remained was to invoke the AJAX loader and aim it at the Perl script that would list the Press Release, using the template that we built. The code looks something like this:


<script type="text/javascript" language="JavaScript1.1">

  document.write(
    '<div id=PressRelText style="' +
      'margin-top: 75px; margin-left: 10px; margin-right: 10px;">' +
    '</div>');
  LoadText('PressRelText',
    '/cgi-bin/InsertDocList.cgi?Type=PR&Count=1&' +
    'Class=NewsText&TplURL=About/PressRel_AJAX.html');

</script>