Previous Page
Next Page

9.1. HTML_AJAX

HTML_AJAX is an AJAX library for PHP licensed under the Library General Public License (LGPL); it provides a JavaScript API and a PHP API. It supports a number of different communication strategies and use cases. It also provides the ability to pass data directly from PHP to JavaScript (and vice versa) using JSON. HTML_AJAX focuses on providing a complete communication layer and tight PHP integration, but it also provides a number of JavaScript utility functions that are useful for debugging and performing common actions in a cross-browser manner.

HTML_AJAX is part of the PHP Extension and Application Repository (PEAR), giving it wide infrastructure support. HTML_AJAX has a small development team, the leader of which is me, the author of this book. This, of course, makes me partial to HTML_AJAX, but HTML_AJAX is widely used and is a good example of an AJAX library that strives for tight language integration.

HTML_AJAX provides many choices in how you use it. This makes it usable for many styles of development but also makes it harder to see where to get started. The three main ways of using HTML_AJAX are as follows:

  • The JavaScript API provides methods to perform general AJAX actions, such as replacing a DOM element with the results of an HTTP request or submitting a form using AJAX. It's targeted at developers who don't mind writing JavaScript code to tie everything together, and it is especially useful when used with behaviors, which allow you to tie JavaScript code to HTML using CSS selectors.

  • The mapped PHP classes' API makes it easy for JavaScript code to call directly into PHP code and get results. It's most useful when you need raw data moved from PHP to JavaScript. It lets you format the data and control its interaction from the JavaScript side.

  • The HTML_AJAX_Action code starts off using mapped PHP classes, but instead of returning raw data, it returns a set of actions to perform against the HTML page; this can include updating the content of nodes, changing the value of an attribute, or running some JavaScript code. This usage pattern allows for a minimal amount of JavaScript to be written and keeps the majority of the logic encapsulated within PHP code.

9.1.1. Installation

Because HTML_AJAX is part of the PEAR project, its installation process is the same as any other PEAR package. You simply need to use the install method of the PEAR package manager, like so:

pear install HTML_AJAX

If you already have HTML_AJAX installed, you can upgrade to the newest version by using this upgrade command:

pear upgrade HTML_AJAX

If you don't have the PEAR package manager installed, you can find installation information on the HTML_AJAX Web site (http://htmlajax.org) or on the PEAR Web site (http://pear.php.net). The HTML_AJAX Web site also provides information on how to install HTML_AJAX without using the PEAR installer, but it's not the recommended method because it makes keeping your installation up-to-date a much more time-consuming process.

To use an HTML_AJAX installation, you will need to provide a way for browsers to access its JavaScript library. The simplest way is to create a page that exposes an instance of the HTML_AJAX_Server class. This class will serve up the JavaScript library from its installation point in the PEAR install directory, which is normally located outside of your document root. This class supports combining multiple libraries and client-side caching to improve performance. Alternatively, you can copy the library from its installation location, the PEAR data directory, to somewhere in your Web root. A single file version of the library named HTML_AJAX.js is provided for this use. A version with comments and whitespace stripped is also provided in HTML_AJAX_lite.js. An example PHP script that can serve up the JavaScript library is shown in Listing 9-1.

Listing 9-1. server.php

<?php
require_once 'HTML/AJAX/Server.php';

$server = new HTML_AJAX_Server();

$server->handleRequest();
?>

You can include the library in an HTML page by loading the page with the client=all query string set. You could also include just the parts of the library you need; examples of both are shown here:

<script type="text/javascript
src="server.php?client=all"></script>

<script type="text/javascript
src="server.php?client=main,request,httpclient,json,loading"></script>

If you want to copy the library, you'll need to find the location of the files. You first find the PEAR data directory by running the following command:

pear config-get data_dir

On most UNIX-like systems, this directory is /usr/share/pear/data. After you find the directory, look in the HTML_AJAX/js directory underneath it. In this directory, you'll see files for each individual part of the library and the combined files as well. To use the library in an HTML file, just include it in the page, like so:

<script type="text/javascript src="pathtolibrary/HTML_AJAX.js"></script>

9.1.2. HTML_AJAX JavaScript API

HTML_AJAX's JavaScript API provides easy access to common AJAX operations. These operations are exposed through the HTML_AJAX static class. The most important methods on this class are as follows:

9.1.2.1. grab

Method signature:

HTML_AJAX.grab(url,callback)

The grab method loads the content from the given URL and either returns it or gives it to a callback. The grab method provides a way to do trivial AJAX requests. The first parameter is the URL to load, and the second is a callback function. The second parameter is optional, and if it's not specified, a synchronous request is performed. Because synchronous requests lock the user interface, you'll usually want to pass in a callback function. The callback function takes a single parameter, which is the content of the loaded URL in string format.

9.1.2.2. replace

Method signature:

HTML_AJAX.replace(id,url)

or

HTML_AJAX.replace(id,className,methodName)

The replace method takes the content of a URL and updates the content of the specified element with the content that has been loaded. The replace method can load a URL directly (the first version of the method call), or it can be used with a PHP class that has been registered on a server calling one of its methods (the second version of the method signature).

9.1.2.3. append

Method signature:

HTML_AJAX.append(id,url)

or

HTML_AJAX.append(id,className,methodName)

The append method works like the replace method, except that instead of replacing all the content of the element specified, it appends the new content to the end of the HTML element. This method can be used to load a URL or against a registered PHP method.

9.1.2.4. formSubmit

Method signature:

HTML_AJAX.formSubmit(form,target,customRequest)

The formSubmit method provides an easy way to submit a form over AJAX. The form parameter is the form to submit over AJAX; it can be the ID of the form or a DOM element. The target parameter is the element whose innerHTML property will be replaced with the results. This can also be an ID or a DOM element, and it is optional; if not specified, the form element is also used as the target. customRequest is also optional and provides a way to pass in a custom Request object, which is useful for setting a custom loading message for this request. The method returns false on a successful submission, allowing it to be used in a form's onsubmit property to cancel the normal form submission because it has already happened in AJAX. This allows you to quickly make an AJAX form by adding an onsubmit handler, like so:

<form onsubmit="return HTML_AJAX.formSubmit(this)">

9.1.2.5. Properties

HTML_AJAX also contains methods that you can override to change the behavior of both the default loading notification and the error handling. In default operation, errors thrown by HTML_AJAX are left for the browser to handle; this usually means a message shows up in a JavaScript error console. You will normally want to handle this in a more informative way because common errors include page loading timeouts and "404 URL not found" messages. If you are making AJAX calls directly into PHP functions, these messages can also include errors from the PHP code that was called. To change the default behavior, you simply need to set a new function on HTML_AJAX.onError. This function can then show a message to the user or try to recover from the problem. Here is a basic custom error handler:

HTML_AJAX.onError = function(e) {
       document.getElementById('error').innerHTML =
              HTML_AJAX_Util.quickPrint(e);
}

Most of the methods in the JavaScript API can take either a URL to which to make a request or a class name and a method name. When a class name and method name are provided, the request is made to the default HTML_AJAX server, where the PHP class that matches the class name is called. To make a class available for an AJAX request, it has to be registered with the server; you would update the server.php file from the installation example, adding a registerClass call before calling handleRequest. Listing 9-2 shows a basic server with a Test class.

Listing 9-2. testServer.php

1  <?php
2  require_once 'HTML/AJAX/Server.php';
3
4  class Test {
5    function serverTime() {
6      return date('Y-m-d H:i:s');
7    }
8
9    function echoString($str) {
10       return 'From Server'.$str;
11    }
12  }
13
14 $server = new HTML_AJAX_Server();
15
16 $server->registerClass(
17   new Test(),
18   'Test',
19   array('serverTime','echoString')
20 );
21 $server->handleRequest();
22 ?>

Like the HTML_AJAX server example in Listing 9-1, this page starts by requiring the HTML_AJAX_Server class. Then, it defines a trivial class called Test (lines 412); this class contains a function that returns the current date from the server and one that echoes a string back to the caller. On line 14, we create a new HTML_AJAX_Server instance, and then on lines 1620, we register an instance of the Test class on the server instance. The first parameter to registerClass is the instance to register (line 17), the second parameter is the name to call it in JavaScript code (line 18), and the last parameter (line 19) is an array of methods to make available. Both the second and third parameters are case sensitive and optional. If they are not provided, PHP's introspection code is used to gather the information. You usually want to provide these options because it guarantees compatibility between PHP4 and PHP5; this compatibility problem exist because PHP4 doesn't keep the case of class/method names, and the later versions of PHP do.

Now that you have a server page that will accept AJAX requests, you're almost ready to use both URL and method uses of HTML_AJAX functions, such as HTML_AJAX.replace. You just set the server to make the class/method requests; this is done by setting HTML_AJAX.defaultServerUrl. Listing 9-3 shows an example of the JavaScript API usage. testServer.php is used to handle class/method calls, and page.html is used for URL calls.

Listing 9-3. HTML_AJAXBasicJSRequest.html

1  <html>
2  <head>
3  <title>HTML_AJAX: Basic Request JavaScript API</title>
4  <script type="text/javascript"
5    src="server.php?client=all"></script>
6
7  <style type="text/css">
8  .target {
9    width: 200px;
10    border: solid 1px black;
11 }
12 </style>
13
14 <script type="text/javascript">
15 HTML_AJAX.defaultServerUrl = 'testServer.php';
16
17 HTML_AJAX.onError = function(e) {
18    document.getElementById('error').innerHTML =
19    HTML_AJAX_Util.quickPrint(e);
20 }
21 </script>
22 </head>
23 <body>
24 <pre id="error">
25 </pre>
26
27 <h3>HTML_AJAX.formSubmit Basic</h3>
28 <form action="form.php"
29      onsubmit="HTML_AJAX.formSubmit(this,this);
30      return false;" method="post">
31
32      <input name="field">
33      <input type="submit">
34 </form>
35
36 <h3>HTML_AJAX.formSubmit Custom loading message</h3>
37 <script type="text/javascript">
38    function customForm(form) {
39      var r = {
40      Open: function() {
41        form.innerHTML = 'Loading Please Wait...';
42      }
43      }
44
45      HTML_AJAX.formSubmit(form,form,r);
46      return false;
47    }
48 </script>
49 <form action="form.php"
50      onsubmit="return customForm(this);"
51      method="post">
52
53    <input name="field">
54    <input type="submit">
55 </form>
56
57 <h3>HTML_AJAX.grab</h3>
58 <a href="#" onclick="
59      HTML_AJAX.grab('page.html',
60      function(r) { alert(r); });
61 ">Grab page.html</a>
62
63 <h3>HTML_AJAX.replace url</h3>
64 <div id="replaceTarget1" class="target"></div>
65 <a href="#" onclick="
66      HTML_AJAX.replace('replaceTarget1','page.html');
67 ">Replace target with page.html</a>
68
69 <h3>HTML_AJAX.replace class/method</h3>
70 <div id="replaceTarget2" class="target"></div>
71 <a href="#" onclick="
72      HTML_AJAX.replace('replaceTarget2',
73      'Test','serverTime');
74 ">Replace target with Test::serverTime</a>
75
76
77 <h3>HTML_AJAX.append url</h3>
78 <div id="appendTarget1" class="target">
79    Current Content: </div>
80 <a href="#" onclick="
81     HTML_AJAX.append('appendTarget1','page.html');
82 ">Append page.html to target</a>
83
84 <h3>HTML_AJAX.append class/method</h3>
85 <div id="appendTarget2" class="target">
86      Current Content: </div>
87 <a href="#" onclick="
88     HTML_AJAX.append('appendTarget2','Test',
89     'echoString','Some Text');
90 ">Append Test::echoString('Some Text') to target</a>
91 </body>
92 </html>

The first section of the listing does the basic setup. On lines 45, it includes the HTML_AJAX JavaScript library. Then on lines 712, it sets up a basic CSS style that will be used to mark elements that will be updated by the AJAX methods. Finally, it finishes the setup by adding the defaultServerUrl (line 15) and adding an error handler, which is useful for debugging problems during the development process.

The defaultServerUrl is used in requests to methods on PHP classes. Lines 2734 set up a form and make it possible to submit it over AJAX. The form has a text box, which is defined on line 32, and a Submit button, which is defined on line 33, but only the input box on line 32 will be submitted. This is because only data from elements with name attributes are submitted. The AJAX activation of the form happens on line 29, which is where we send the onsubmit method to HTML_AJAX.formSubmit. The current form is used both for the form to submit and the element to update the innerHTML with the results. This means that the form tag will still exist, but all its children (lines 5354) will be replaced. Also note that false is returned from the onsubmit method; this prevents the normal form submission from happening. The method and action attributes of the form are read by formSubmit, and they are used to determine where the form is submitted.

Lines 3655 show a more advanced case of AJAX form submission. The form is set up the same way, but instead of calling formSubmit in the onsubmit method, we call a custom function instead. This function, which is defined on lines 3847, defines some options for the form submission and then runs HTML_AJAX. formSubmit (line 45). These extra options are passed in as the third parameter; these options allow you to set any attribute on the Request object that will be built to submit this form. Some commonly overridden attributes are the Open and Load event handlers and the RequestUrl. In this example, we're setting only the Open event handler (lines 4042). This is called when we open the HTTP connection to the server, and it is generally used to provide custom loading messages. Normally, this event handler is matched with the Load event handler, which is called at the end of the request, but that's not needed in this case, because the Open function replaces the contents of the form, and this message will then be replaced by the form's results.

Lines 5761 show an example of the HTML_AJAX.grab function. This simple function is used when you want to make a GET request to a page and perform an action on its results. The second parameter (line 60) is the callback function; in this case, it just creates an alert box with the value of the page. If this parameter is left out, a synchronous requestinstead of an asynchronous oneis made.

There are two examples of the HTML_AJAX.replace function. The first one is on lines 6367 and loads a URL and then replaces the contents of a DIV with the new content from the server. The second example is on lines 6974 and calls a PHP method and replaces the contents of a DIV with the results from the PHP method call. In URL mode, replace takes two parameters (line 66): the ID of the element to replace and the URL to which to make the request. In PHP method mode, replace takes three parameters: The first is the ID of the element to replace, the second is the PHP class, and the third is a method on that class. The URL to use for this request is determined by the HTML_AJAX.defaultServerUrl variable, which was set on line 15. If the class and method haven't been registered for AJAX access by the server, an error will be thrown; this error can then by handled by the HTML_AJAX.onError method.

The final sets of examples are for the HTML_AJAX.append method (lines 7790). This method works exactly like the HTML_AJAX.replace method, except that instead of replacing the innerHTML of the specified element, the new content is appended to innerHTML. If you need more complicated replacement rules, use the grab method and provide a custom callback function with the needed logic.

9.1.3. Remote Stub AJAX

As was shown in testServer.php in Listing 9-2, HTML_AJAX has the ability to make PHP classes directly available to AJAX calls from JavaScript. By default, HTML_AJAX accomplishes this by passing JSON-encoded messages between the server and the client. This allows all serializable PHP and JavaScript data types (resources in PHP and DOM objects in JavaScript can't be sent) to be seamlessly sent between the client and the server. Although these PHP functions can be accessed through HTML_AJAX's JavaScript API, they also offer another possibility: generated JavaScript classes that mimic the API of their PHP counterparts.

This system allows you to have a JavaScript class with the same methods that were registered on the server. For example, testServer.php registered the Test class; this class has two methods, serverTime and echoString, so after including the generated JavaScript stub file, you now have a class called Test in JavaScript with serverTime and echoString methods. A call to either of these methods will automatically be sent over XMLHttpRequest to the PHP server; the matching PHP method will then be called, and its results will be sent back to JavaScript where they will be passed to a callback method.

To import the JavaScript stub class, you simply add stub=className to your inclusion of testServer.php. You can choose to combine this with the request you're already doing for the client libraries, or you can add a second JavaScript include to handle this. While including the JavaScript library and the stubs in one request is handy, it's not always the best approach from a caching standpoint. HTML_AJAX includes code that causes client Web browsers to cache JavaScript served up by the HTML_AJAX_Server class whenever possible, but for this to work, the content needs to remain consistent. If you are requesting a different stub class on each page load, you'll defeat this cache even though only a small part of the requested content is changing.

When you create an instance of the stub class, you pass in an object that provides the callback methods. Each method has its own callback named the same as the method that was called. These callback methods take a single parameter, which contains the results sent from the PHP code. The callback class can also provide custom handlers that work the same as the general handlers in the HTML_AJAX class. This allows handling errors and loading messages specifically for this class. Listing 9-4 shows an example that uses the Test class provided by testServer.php.

Listing 9-4. HTML_AJAXStubAJAX.html

1  <html>
2  <head>
3  <title>HTML_AJAX: Stub AJAX</title>
4  <script type="text/javascript"
5      src="testServer.php?client=all"></script>
6  <script type="text/javascript"
7      src="testServer.php?stub=Test"></script>
8
9  <style type="text/css">
10 .target {
11   width: 200px;
12    border: solid 1px black;
13 }
14 </style>
15
16 <script type="text/javascript">
17 var callback = {
18 serverTime: function(result) {
19      document.getElementById('target').innerHTML
20          = 'Server Time:<br>' + result;
21 },
22 echoString: function(result) {
23      document.getElementById('target').innerHTML
24          = 'Echo String:<br>' +result;
25      }
26 }
27
28 var remote = new Test(callback);
29 </script>
30 </head>
31 <body>
32
33 <a href="#" onclick="remote.serverTime()"
34      >Show Server Time</a><br>
35
36 <a href="#" onclick="remote.echoString('Test')"
37      >Echo a String</a><br>
38
39 <div class="target" id="target"></div>
40
41 </body>
42 </html>

Listing 9-4 allows you to run the serverTime method, which displays the formatted date and time from the server, and echoString, which returns the passed in string with From Server prepended to it. The page starts with a basic setup; lines 56 include the JavaScript client library; this library provides the automatically generated stub class, which is included on lines 6 and 7. The parameters to both these includes follow the same syntax, so we could have used the all keyword instead of the class name on line 7. You can also uses a comma-separated list for both stub and client; this is useful for including a specific set of stub classes (stub=Test,OtherClass) or to include a specific portion of the JavaScript library (client=main,util). The header also includes a small amount of CSS (lines 914) used to style the element to which we will be outputting messages.

Lines 1629 include the JavaScript code that provides functionality to this page. First it defines a setup of callback functions (lines 1726); then it creates an instance of the remote stub class (line 28). In the callback definition, we define one method for each method on the stub class. Lines 1821 define the callback for the serverTime method; this code outputs the results of serverTime() to the target DIV prepended with a small message. Lines 2226 do the same tasks for the echoString method, except that they use a different label. Line 28 finishes the process by creating an instance of the remote stub passing in the callback variable defined above it. If no callback was passed into the constructor, the remote class would still work, but it would run in synchronous mode, returning results directly and locking the user interface until the request was done.

The rest of the listing creates the user interface for the page, creating links to call the methods on the remote class. Line 33 is for the serverTime method, and line 36 is for the echoString method. Line 39 creates the output DIV, using the CSS rule defined earlier to give it a border.

9.1.4. Using HTML_AJAX_Action

HTML_AJAX_Action is a PHP class that allows you to specify the JavaScript callback of a PHP function from within PHP code. On the JavaScript side, you create a remote stub class, but instead of passing in an object containing your custom callback functions, you pass in an empty hash, like so:

var remote = new remoteClass({});

The PHP class that you are registering for remote access returns an instance of HTML_AJAX_Action to specify what the JavaScript should do. HTML_AJAX_Action provides the ability to set attributes on arbitrary DOM nodes, create new DOM nodes, and run any JavaScript code. When working with DOM attributes, you can prepend to the property, append to it, or clear it. These operations are most useful with the innerHTML property, but they can also be useful with other properties that can take multiple values. One example of such a property is className. Listing 9-5 shows an example of a PHP class that returns HTML_AJAX_Action events.

Listing 9-5. Action.class.php

1  <?php
2  require_once 'HTML/AJAX/Action.php';
3
4  class Action {
5    function changeColor() {
6      $haa = new HTML_AJAX_Action();
7
8      // pick a random color
9      $r = rand(0,255);
10      $g = rand(0,255);
11      $b = rand(0,255);
12      $haa->assignAttr('target',
13              array('style' => "color: rgb($r,$g,$b)"));
14      return $haa;
15    }
16
17      function alert() {
18      $haa = new HTML_AJAX_Action();
19
20          $haa->insertAlert('This is a message from PHP');
21          return $haa;
22      }
23 }

Because we are going to be creating HTML_AJAX_Action objects, we need to start out by requiring the needed code; this is done on line 2. Then, we define the Action class. The class contains two methods. The first method, changeColor (lines 515), uses the assignAttr method to set the style attribute of the target node. To do this, we create a new HTML_AJAX_Action instance (line 6), create three random values to use as our color (lines 811) and then run assignAttr (line 12). The first parameter to assignAttr is the ID of the element to update; the second parameter is an associative array of attributes to update. The key of the array is the attribute, with its value being the new value to set. You could include multiple attributes to set, including innerHTML. To finish the method, we return the HTML_AJAX_Action instance on which we've been working (line 14).

The second method alert (lines 1722) uses HTML_AJAX_Action's ability to inject new JavaScript into the page. On line 18, we create a new HTML_AJAX_Action instance, and then on line 20, we call its insertAlert method. The method takes a single parameter, which is the message to alert. We also could have used the insertJavaScript method and written alert("message"); directly. The function finishes by returning the HTML_AJAX_Action instance (line 21). While not shown here, HTML_AJAX_Action allows you to combine multiple actions in one method; you just keep calling the various methods on the instance before returning it. The order that you call the methods will be the order that the actions are processed in the browser.

9.1.5. JavaScript Behaviors

JavaScript Behaviors are pieces of JavaScript code applied to DOM elements through the use of CSS selectors. They are an effective way to keep HTML code free from hundreds of onclick attributes. HTML_AJAX includes behavior support through its inclusion of a modified version of Ben Nolan's Behavior library. Behavior is extremely easy to use; it has one public method, Behavior.register, which takes a CSS selector as its first parameter and a JavaScript function that is run on each matching element. These registrations can take place in the header of the HTML document. A good strategy is to put them into an include file and create a common set of behaviors to use throughout a site just like you would for CSS. Listing 9-6 gives an example that shows the basics of JavaScript behaviors.

Listing 9-6. HTML_AJAXBehavior.html

1  <html>
2  <head>
3  <title>HTML_AJAX: Behavior</title>
4  <script type="text/javascript"
5    src="server.php?client=all"></script>
6
7  <script type="text/javascript">
8  Behavior.register(
9      ".alert",
10      function(element) {
11          element.onclick = function() {
12              alert('I alert on click');
13          }
14      }
15 );
16  Behavior.register(
17      ".green",
18      function(element) {

19          element.onmouseover = function() {
20              element.style.color = 'green';
21          }
22      }
23 );
24 </script>
25 </head>
26 <body>
27 <p class="alert">
28 I am a paragraph that alerts when you click on me
29 </p>
30 <p class=" alert green">
31 I am a paragraph that alerts on click
32 and turns green on mouse over
33 </p>
34 </body>
35 </html>

Behavior is provided by HTML_AJAX, so we get support for it when we include the entire HTML_AJAX JavaScript library; this is done on lines 4 and 5. On lines 724, we define two JavaScript behaviors. The first behavior (lines 815) applies to the CSS selector .alert, which is any element with a class of alert. On the page load, Behavior passes each matching class to the processing function (lines 1014); this function adds an onclick event handler, which alerts a message. The second behavior (lines 1623) has a similar selector; this time, the behavior applies to the green class. The processing function for it (lines 1822) adds an onmouseover handler, which sets the color of the element to green (line 20).

The rest of the page (lines 2635) provides some sample HTML elements to which to apply the rules. On lines 2729, we define a paragraph element with the class alert; when you click this class, it will alert a message because of the behavior applied to elements within the alert class. Lines 3033 define another paragraph. This paragraph has two classes (in CSS, multiple classes are separated by spaces): alert and green. This value for class means it will get both behaviors, alerting a message when clicked and turning green on a mouse over.

9.1.6. JavaScript Utility Methods

HTML_AJAX contains a number of JavaScript utility methods located in the HTML_AJAX_Util class. Some of these methods, such as quickPrint and varDump, are useful for debugging, whereas others help in cross-browser compatibility. Some of the most widely applicable functions are shown here.

9.1.6.1. quickPrint

Method signature:

HTML_AJAX_Util.quickPrint(input)

The quickPrint method takes an input variable and iterates over it, printing out each member on its own line in the format of name:value. This is useful for quickly identifying the values of the properties of an object. The input is an object written in object literal notation. Example output of quickPrint follows.

Input: {property1:'one',innerHash:[4,5,6,7],anotherProp:true}

Output:
property1:one
innerHash:4,5,6,7
anotherProp:true

9.1.6.2. varDump

Method signature:

HTML_AJAX_Util.varDump(input)

varDump takes an input variable and recurses over it, producing an output similar to PHP's var_dump method, including type information. When dealing with DOM objects or other variables that have a large number of children, you will get an extremely large output from varDump. Example output of varDump follows:

Input: {property1:'one',innerHash:[4,5,6,7],anotherProp:true}

Output:
object(Object) (3) {
  ["property1"]=>
  string(3) "one"
  ["innerHash"]=>
  array(5) {
    [0]=>
    number(4)
    [1]=>
    number(5)
    [2]=>
    number(6)
    [3]=>
    number(7)

    ["______array"]=>
    string(11) "______array"
  }
  ["anotherProp"]=>
  boolean(true)
}

9.1.6.3. getElementsByClassName

Method signature:

HTML_AJAX_Util.getElementsByClassName('CSSClass',parent);

The getElementByClassName function allows you to get an array of the DOM elements that have the provided CSS class. The second parameter, parent, is optional; if specified, the search happens against the child elements of the parent node. If it's not specified, the search is done against the entire document. The document we're searching against contains the following HTML:

<p class="test">Test Nodes</p>
<div class="test"></div>
<span class="test"></div>
<div class="test2"></div>

To find the nodes in the document with a class of test, you would run the following:

var nodes = HTML_AJAX_Util.getElementsByClassName('test');

This gives you an array with three elements. You could then loop over this array, changing the style of the elements or updating their content using innerHTML.

9.1.7. PHP Utility Methods

HTML_AJAX also includes a class of PHP utility methods that help perform common functions related to JavaScript generation. The methods are located in the HTML_AJAX_Helper class, which is included in a PHP script by use of the following:

require_once 'HTML/AJAX/Helper.php';

The most commonly used methods are jsonEncode and encloseInScript. The jsonEncode method takes a PHP variable and returns a JSON string, which can be outputted directly to JavaScript, like so:

var jsVar = <?php echo $helper->jsonEncode($phpVariable); ?>;

The encloseInScript method takes a string input, encloses it in JavaScript script tags, and then returns it. It is commonly used when generating JavaScript from PHP, which would be like this:

echo $helper->encloseInScript($generateJavaScript);

9.1.8. HTML_AJAX Development Tips

HTML_AJAX can be used out of the box, but if it doesn't meet your needs, it can also be used as a building block for your own custom AJAX library. The following are some tips to keep in mind while using HTML_AJAX:

  • The HTML_AJAX wiki (http://htmlajax.org) contains more information about HTML_AJAX, including a mailing list by which you can ask questions of its developers.

  • If you register lots of classes with HTML_AJAX_Server, you can use its initMethod functionality to include classes only as they are requested, decreasing the amount of PHP processing done per request.

  • HTML_AJAX turns native data types into strings using serialization classes; this process is customizable, so if JSON doesn't meet your needs, you can replace it with whatever does.


Previous Page
Next Page