Chapter 20
AHAH—Asynchronous HTML and HTTP

What You’ll Learn in This Chapter:

image Introducing AHAH

image Creating a Small Library for AHAH

image Using myAHAHlib.js

In this chapter you will learn how to use AHAH (Asynchronous HTML and HTTP) to build Ajax-style applications without using XML.

Introducing AHAH

You saw in Chapter 19, “Returning Data as Text,” just how much can be achieved with an Ajax application without using any XML at all. Many tasks, from simply updating the text on a page to dealing with complicated data structures, can be carried out using only the text string whose value is returned in the XMLHTTPRequest object’s responseText property.

It is possible to build complete and useful applications without any XML at all. In fact, the term AHAH (Asynchronous HTML and HTTP) has been coined for just such applications.

This chapter takes the concepts of Chapter 19 a little further, examining in more detail where—and how—AHAH can be applied.

Image

This technique, a kind of subset of Ajax, has been given various acronyms. These include AHAH (asynchronous HTML and HTTP), JAH (Just Asynchronous HTML), and HAJ (HTML And JavaScript). In this book we’ll refer to it as AHAH.

Why Use AHAH Instead of Ajax?

There is no doubt that XML is an important technology with diverse and powerful capabilities. For complex Ajax applications with sophisticated data structures it may well be the best—or perhaps the only—option. However, using XML can sometimes complicate the design of an application, including:

image Work involved in the design of custom schemas for XML data.

image Cross-browser compatibility issues when using JavaScript’s DOM methods.

image Performance may suffer from having to carry out processor-intensive XML parsing.

Using AHAH can help you avoid these headaches, while offering a few more advantages, too:

image Easy reworking of some preexisting web pages.

image HTML can be easier to fault-find than XML.

image Use of CSS to style the returned information, rather than having to use XSLT.

Image

XSLT is a transformation language used to convert XML documents into other formats—for example, into HTML suitable for a browser to display.

In the following sections we’ll package our AHAH scripts into a neat external JavaScript file that we can call from our applications.

Creating a Small Library for AHAH

The Ajax applications examined in the last couple of chapters, although complete and functional, involved embedding a lot of JavaScript code into our pages. As you have seen, each application tends to contain similar functions:

image A method to create an instance of the XMLHTTPRequest object, configure it, and send it

image A callback function to deal with the returned text contained in the responseText property

You can abstract these functions into simple JavaScript function calls, especially in cases where you simply want to update a single page element with a new value returned from the server.

Introducing myAHAHlib.js

Consider Listing 20.1; most of this code will be instantly recognizable to you.

Listing 20.1 myAHAHlib.js

function callAHAH(url, pageElement, callMessage) {
     document.getElementById(pageElement) .innerHTML = callMessage;
     try {
     req = new XMLHttpRequest(); /* e.g. Firefox */
     } catch(e) {
       try {
       req = new ActiveXObject(“Msxml2.XMLHTTP”);
  /* some versions IE */
       } catch (e) {
         try {
         req = new ActiveXObject(“Microsoft.XMLHTTP”);
  /* some versions IE */
         } catch (E) {
           req = false;
        }
      }
    }
    req.onreadystatechange = function() {responseAHAH(pageElement);};
     req.open(“GET”,url,true);
     req.send(null);
  }
function responseAHAH(pageElement) {
   var output = ‘’;
   if(req.readyState == 4) {
     if(req.status == 200) {
        output = req.responseText;
        document.getElementById(pageElement) .innerHTML = output;
         }
       }
     }

The function callAHAH() encapsulates the tasks of creating an instance of the XMLHTTPRequest object, declaring the callback function, and sending the request.

Note that instead of simply declaring

req.onreadystatechange = responseAHAH;

we instead used the JavaScript construct

req.onreadystatechange = function() {responseAHAH(pageElement);};

This type of declaration allows us to pass an argument to the declared function, in this case identifying the page element to be updated.

callAHAH() also accepts an additional argument, callMessage. This argument contains a string defining the content that should be displayed in the target element while we await the outcome of the server request. This provides a degree of feedback for the user, indicating that something is happening on the page. In practice this may be a line of text, such as

‘Updating page; please wait a moment ….’

Once again, however, you may choose to embed some HTML code into this string. Using an animated GIF image within an <img> element provides an effective way of warning a user that a process is underway.

The callback function responseAHAH() carries out the specific task of applying the string returned in the responseText property to the innerHTML property of the selected page element pageElement:

output = req.responseText;
document.getElementById(pageElement).innerHTML = output;

This code has been packaged into a file named myAHAHlib.js, which you can call from an HTML page, thus making the functions available to your AHAH application. The next section shows some examples of its use.

Using myAHAHlib.js

In Part II we encountered the concept of JavaScript functions being located in an external file that is referred to within our page.

That’s how we’ll use our new file myAHAHlib.js, using a statement in this form:

<SCRIPT language=”JavaScript” SRC=”myAHAHlib.js”></SCRIPT>

We will then be at liberty to call the functions within the script whenever we want.

The following is the skeleton source code of such an HTML page:

<html>
<head>
<title>Another Ajax Application</title>
<SCRIPT language=”JavaScript” SRC=”myAHAHlib.js”></SCRIPT>
</head>
<body>
<form>
<input type=”button” onClick= ”callAHAH(‘serverscript.php?parameter=x’, ‘displaydiv’, ‘Please wait – page updating …’)” >
This is the place where the server response
will be posted:<br>
<div id=”displaydiv”></div>
</form>
</body>
</html>

In this simple HTML page, a button element is used to create the event that causes the callAHAH() method to be called. This method places the text string

‘Please wait – page updating …’

in the <div> element having id displaydiv and sends the asynchronous server call to the URL serverscript.php?parameter=x.

When responseAHAH() detects that the server has completed its response, the <div> element’s content is updated using the value stored in responseText; instead of showing the “please wait” message, the <div> now displays whatever text the server has returned.

Applying myAHAHlib.js in a Project

We can demonstrate these techniques with a further simple Ajax application. This time, we’ll build a script to grab the ‘keywords’ metatag information from a user-entered URL.

image

Metatags are optional HTML container elements in the <head> section of an HTML page. They contain data about the web page that is useful to search engines and indexes in deciding how the page’s content should be classified. The ‘keywords’ metatag, where present, typically contains a comma-separated list of words with meanings relevant to the site content. An example of a ‘keywords’ metatag might look like this:
<meta name=”keywords” content=”programming, design, development, Ajax, JavaScript, XMLHTTPRequest, script”>

Listing 20.2 shows the HTML code.

Listing 20.2 getkeywords.html

<html> 
<head>
<title>A ‘Keywords’ Metatag Grabber</title>
<SCRIPT language=”JavaScript” SRC=”myAHAHlib.js”>
</SCRIPT>
</head>
<body>
<script type=”text/javascript” src=”ahahLib.js”>
</script>
<form>
<table>
<tr>
  <td>     
       URL: http://   
  </td>   
  <td>      
    <input type=”text” id=”myurl” name=”myurl” size=30>
    <input type=”button” onclick = ”callAHAH(‘keywords.php?url=’+document .getElementById(‘myurl’).value,‘displaydiv’, ‘Please wait; loading content …’)” value=”Fetch”>
   </td> 
</tr>
<tr><td colspan=2 height=50 id=”displaydiv”></td></tr></table>
</form>
</body>
</html>

Finally, consider the server-side script:

<?php
$tags = @get_meta_tags(‘http://’.$url);
$result = $tags[‘keywords’];
if(strlen($result) > 0)
{
   echo $result;
} else {
  echo “No keywords metatag is available”;
}
?>

We present the selected URL to the PHP method get_meta_tags() as an argument:

$tags = @get_meta_tags(‘http://’.$url);

This method is specifically designed to parse the metatag information from HTML pages in the form of an associative array. In this script, the array is given the name $tags, and we can recover the ‘keywords’ metatag by examining the array entry $tags[‘keywords’]; we can then check for the presence or absence of a ‘key-words’ metatag by measuring the length of the returned string using PHP’s strlen() method.

Image

The @ character placed before a PHP method tells the PHP interpreter not to output an error message if the method should encounter a problem during execution. We require it in this instance because not all web pages contain a ‘keywords’ metatag; in the cases where none exists, we would prefer the method to return an empty string so that we can add our own error handling.

When the file getkeywords.html is first loaded into the browser, we are presented with the display shown in Figure 20.1.

Figure 20.1 The browser display after first loading the application.

image

Here we are invited to enter a URL. When we then click on the Fetch button, callAHAH() is executed and sends our chosen URL as a parameter to the server-side script. At the same time, the message “Please wait; loading content … “ is placed in the <div> container. Although possibly only visible for a fraction of a second, we now have a display such as that shown in Figure 20.2.

Figure 20.2 Awaiting the server response.

image

Finally, when the server call has concluded, the contents of the responseText property are loaded into the <div> container, producing the display of Figure 20.3.

Figure 20.3 The keywords are successfully returned.

image

Image

One option we haven’t yet considered is the idea of passing back JavaScript code within responseText. Because JavaScript source code (like everything else in an HTML page) is made up of statements written in plain text, you can return JavaScript source from the server in the responseText property.

You can then execute this JavaScript code using JavaScript’s eval() method:

 eval(object.responseText);

Consider the situation where your server script returns the string:

 “alert(‘Hello World!);”

In this case the eval() method would execute the content as a JavaScript statement, creating a dialog saying ‘Hello World!’ with an OK button.

Summary

It will hopefully have become clear, in the course of this chapter and Chapter 19, that Ajax can achieve a lot of functionality without using any XML at all.

By carefully using combinations of client-side coding in JavaScript and server-side scripting in your chosen language, you can create data schemes of high complexity.

In simpler applications, where all you want to do is update the text of page elements, the XMLHTTPRequest object’s functionality may be abstracted into a JavaScript function library and called from an HTML page via straightforward methods.

For some tasks, however, you need to leverage the power of XML. We’ll look at this subject in Chapter 21, “Returning Data as XML.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.227.231