Introduction to PEAR
As you might imagine, there are plenty of open source libraries available to the PHP language. In fact, one might say that PHP's success as a language is due to the multitude of available resources and the amazing, helpful online community. Because of the large amount of open source development libraries, implementing clean, effective code into your Ajax-based applications is a mere Google search away. However, like anything, some code libraries/repositories are better than others.
One of the more robust extension packages that has been around for quite a while is that of the PEAR (PHP Extension and Application Repository) package. PEAR is more than just a PHP framework—it is a whole model for proper coding practices. By using the PEAR framework, you give yourself a leg up by providing extensions that will help to create clean, customizable layouts for your Ajax applications.
How you get started with PEAR depends on your version of PHP. If you are using PHP 4.3.1 or above, the PEAR extensions are available to you straight out of the box. Users of PHP versions prior to 4.3.1 can download the entire set from the PEAR web site, at http://pear.php.net.
The basic installation of newer versions of PHP comes with a fairly large assortment of PEAR modules ready to go, but you can still visit the PEAR web site to download whichever extensions you deem necessary.
Making use of the PEAR code base is quite easy. The extensions in PEAR require the generic PEAR.php file that is included into the extension-based code. From there you merely have to include the extension that you require, and you have full access to the functionality contained within. While there are plenty of ways to make use of PEAR with Ajax to create highly functional and ergonomic web-based applications, let's start with a fairly simple one: HTML_Table. If you don't have the HTML_Table module, you can get it from http://pear.php.net/package/html_table.
The way to install the PEAR modules depends on the platform you are using. For instance, in Linux (once you have PEAR installed on your server), the package can be installed from your command line by using the following command:
pear install html_table
For Windows users, the process is largely the same and can be done from your command line. A simple Google search will allow you to pinpoint an easy installation method for your platform of choice.
In order to use HTML_Table, you're also required to have HTML_Common, so be sure to install this package as well, using the same process as detailed previously.
HTML_Table
The HTML_Table PEAR module is a code set designed to allow you to create and modify tables using PHP code. Basically, you set up the cells and rows you want, and then use the PHP class to output the table. By using this module, you will get a clean, easily maintained table every time.
In order to show off what's possible when you combine the efficiency and maintainability of HTML_Table with Ajax functionality, I've created something of a number calculator. While it's not exactly Microsoft Excel, this example does an adequate job of showing how to create and use the HTML_Table module, and then use it to perform Ajax-based functionality that is efficient, ergonomic, and easy for the user to make use of. This example is shown in Figures 8-5 and 8-6.
|
24 I | |||
|
Totals | |||
Figure 8-5. Simply enter your values like you would in a spreadsheet application.
|
3 |
5 |
8 | |||
|
24 |
12 |
6 | |||
|
25 |
24 |
T | |||
|
Totals | |||||
|
52 |
41 |
14 | |||
Figure 8-6. Our HTML_Table application automatically adds up the values.
The HTML_Table application, as shown in Figures 8-5 and 8-6, works by creating a set of fields that the user can make use of to calculate a sum of the rows. You have seen what it looks like—now let's have a look at how it works. The first aspect of the code that you need to look at is the sample8_2.php file. It creates an instance of an HTML_Table object that you will use as the framework for your application. Consider the following block of code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.wB.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>
<title>Sample 8_2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="xmlhttp.js"></script> <script type="text/javascript" src="functions.js"></script> </head> <body> <?php
// Set the size of the table $maxrows = 3; $maxcols = 4;
// Create the table and set its properties require_once ("HTML/Table.php");
$table = new HTML_Table(array('cellpadding' => 0,
$table->setCaption ("HTML_Table use with AJAX");
//Create our data set of empty rows. $counter = 0;
$event = sprintf('createtext(this, %d, %d, %d, %d)', $j,
$counter, $maxcols, $maxrows);
//Create a "totals" separator. $totdata = array ("Totals");
$table->addRow($totdata, array('colspan' => $maxcols,
'align' => 'center', 'bgcolor' => '#c0c0c0', 'color' => '#fff'));
//Then create the totals boxes. $totcounter = 0;
$attrs = array('id' => 'tot' . $totcounter, 'height' => '20',
'width' => intval(100 / $maxcols) . '%', 'bgcolor' => '#eee', 'align' => 'center');
$table->setCellAttributes($maxcols, $j, $attrs); $totcounter++;
As you can see, by making use of the ability to set attributes within each individual cell of the table, you can create an Ajax application using a PHP module from PEAR. While that certainly seems like a mouthful, it is not necessarily all that complicated. The code starts by initializing a new HTML_Table object. You then build upon it from there by supplying it a caption and gradually building the rows you want.
There are two crucial portions of this script, however. The first to note is when you are creating your first set of empty cells. Notice that, within the first call to the setCell^ Attributes function, you assign the onclick value to call the createtext function. What this will do is assign a value to each cell that tells it to call the createtext function whenever the cell is clicked. The next crucial element of this script happens when you create the Totals boxes. You will notice that the id value is assigned to a specific number. This will be crucial when loading in the calculated totals from your Ajax-based scripts.
The last piece of functionality that occurs is the call to the toHTML method, which converts this block of PHP code into an HTML table. At this point, your framework has been set. Let's look at your functions.js file to see how the Ajax-based functionality is achieved.
The first function you want to have a look at is the createtext function. This function takes in as arguments the location to create the text box, the column this box is part of, and the unique number of the box itself. Basically, when a user clicks on a cell in your table, this function is called. If the box has not yet been created, you will dynamically create the box within the cell. You use CSS to mask the box (no border, same width and height) so that the user does not know that a box has been created.
Once the box has been created, you assign focus to it and allow the user to enter some values. When the user finishes entering the values and clicks off of the box, the loadtotals function is called:
//functions.js function createtext (where, col, counter, numCols, numRows) {
if (where.innerHTML == '' || where.innerHTML == ' ') {
var theEvent = 'loadTotals(' + col + ', ' + numCols + ', ' + numRows + ')';
where.innerHTML = '<input id="' + id + '" type="text" class="noshow"' + ' onblur="' + theEvent + '" />';
document.getElementById(id).focus();
The loadtotals function is not so much complicated as it is a validation nightmare. Because the user could potentially enter any form of data, and you only want integer values (in this case), you must be very careful how you attempt this. Another hurdle to the execution of this script can arise if the function tries to perform the addition before all of the relevant boxes are created. As you can see, there is a bit of validation to do.
In order to calculate the total of the column, you first run a loop through each column by going through the number of rows in a column. Now, before you can add up all of the values, a check must be done to ensure that the three values to be added are of an Integer type. You can use the isNaN function to determine if a non-Integer has slipped through the cracks, and if so, default said value to zero again. It is also imperative, when calculating data that will be at first interpreted as a String data type, to change the String data type into a numerical data type, such as Integer. This can be done in JavaScript using the parseInt function, as shown in the following code example. At this point, you simply need to add up your Integer values and submit the sum to the column total cell's innerHTML property, thereby finishing the calculation.
function loadTotals(col, numCols, numRows)
for (var row = 0; row < numRows; row++) { cellId = row * numCols + col + 1;
var elt = document.getElementById(id);
val = parseInt(elt.value); if (!isNaN(val)) total += val;
document.getElementById('tot' + col).innerHTML = total;
Post a comment