Original URL: http://www.theregister.co.uk/2007/11/20/creating_jsf_portlets/

Xajax and PHP: JavaScript without the pain

Automatic for the people

By Deepak Vohra

Posted in Software, 20th November 2007 03:43 GMT

Hands on When it comes to Web 2.0, PHP’s seen it all before. Birthed before the last great internet boom, PHP has matured and is now one of a triumvirate of languages synonymous with today’s craze for building web sites and online services with Linux and MySQL.

While it shares LAMP honors with Perl and Python, though, PHP has become the most commonly used server-side platforms for Ajax and, of all the Ajax frameworks for PHP, Xajax is the most commonly used. If you are not familiar with JavaScript, which forms the basis of Ajax, but still would like to use Ajax with PHP, Xajax is the obvious choice because Xajax generates the required JavaScript for you.

In this Hands On, I’ll demonstrate a simple way to use Ajax and PHP within Xajax, with an Oracle database, while sidestepping the need for the problematic XMLHttpRequest.

Xajax backrounder

Xajax is an open source, object oriented, PHP class library that can be used with PHP scripts for server-side processing. Xajax is used to communicate asynchronously between a client- and a server-side application comprised of PHP scripts, and generates JavaScript wrapper functions so that PHP functions on the server can be accessed from a client application.

When a client application invokes the wrapper functions, a XMLHttpRequest object is initiated and a XMLHttpRequest object is sent to the server. On the server, the Xajax object receives the XMLHttpRequest and invokes the PHP functions corresponding to the JavaScript wrapper functions.

The default request type of PHP functions registered through Xajax is POST. The PHP functions return an XML response that is returned to the client application by the Xajax object. Based on the instructions in the XML response, the Xajax’s JavaScript message pump updates the content of the client input page. Xajax has a feature that, data is updated only if data has been modified.

Download and go

As Xajax is a PHP class library, first download and install PHP 5 and Apache2 HTTP server as explained in an earlier, article on PHP. The example application shall store and fetch data from Oracle database 10g. Therefore, enable the Oracle database extension in the php.ini configuration file.

extension=php_oci8.dll

Create an example database table in OE schema with a PHP script, Table.php, which is available in resources zip. Download Xajax0.2.4/0.2.5. Extract xajax_0.2.4.zip file to the C:/Program Files/Apache Group/Apache2/htdocs directory.

Send an Ajax request

We shall create an Xajax application to validate an input field in a form. The input form takes data to add a catalog entry to the database table Catalog. As a user begins to enter data in the input field Catalog Id, a XMLHttpRequest is sent to the server to validate the Catalog Id value added.

If the Catalog Id is not already defined in the database, a message "Catalog Id is Valid" gets displayed. If the Catalog Id is already defined in the database, a message "Catalog Id is not Valid" gets displayed, the Create Catalog button gets disabled and field values for the Catalog Id get added to the form.

The xajax PHP object performs the function of an intermediary between the client application and the server. In the Xajax application PHP script create a xajax object.

$xajax = new xajax();

The server side processing is performed by PHP functions. Create PHP functions validateCatalogId($formValues) and updateCatalog($formValues). Both these functions take a formValues parameter.

function validateCatalogId($formValues){}
function updateCatalog($formValues){}

Register the PHP functions with the xajax object using the registerFunction() method. The xajax object creates wrapper functions for the PHP functions that may be invoked from a PHP script or an input form event handler.

$xajax->registerFunction("validateCatalogId");
$xajax->registerFunction("updateCatalog");

Xajax generates asynchronous wrapper functions for the registered PHP functions. A wrapper function name uses the format phpfunction. Variable phpfunction is a server-side PHP function for which a wrapper function is to be defined. Xajax provides asynchronous form processing with the getFormValues(string formId) method. Using the getFormValues() method, an array of form field values may be submitted as an argument to a xajax asynchronous function.

Sections of a form may also be submitted instead of the complete form with the getFormValues(string formID ,boolean submitDisabledElements, string prefix]) function. The prefix parameter specifies that only form elements starting with that prefix should be submitted. Boolean parameter submitDisabledElementsspecifies if disabled elements are to be submitted. PHP functions validateCatalogId and updateCatalog define a parameter for an array of form field values. Before a XMLHttpRequestis initiated, specify the xajax object to handle requests with the processRequests() function.

$xajax->processRequests();

Also specify in the tags of the input form that Xajax should generate any required JavaScript after an XML response has been sent back from the server.

<?php $xajax->printJavascript('./xajax');
?>

A XMLHttpRequest is initiated by a client application. In the example application, a XMLHttpRequest is initiated by the onkeyup event handler in input field catalogId.

<tr><td>Catalog Id:</td><td><input    type="text"
            size="20"  
              id="catalogId"
            name="catalogId"
    autocomplete="off"
         onkeyup="xajax_validateCatalogId(xajax.getFormValues('validationForm'));"></td>
         <td><div id="validationMessage"></div></td>
</tr>

The input field invokes the wrapper function xajax_validateCatalog with an array of form field values as a parameter. The wrapper functions send a XMLHttpReques to the server. The xajaxobject receives the XMLHttpRequest and invokes the corresponding PHP function validateCatalogId($formValues).

Process an Ajax request

Xajax provides the xajaxResponseclass to send a response to the client application. In the validateCatalogId function, create a xajaxResponse object.

$objResponse = new xajaxResponse();

The validateCatalogId function validates a Catalog Id value added in the input form. From the $formValues array retrieve the value of the catalogId field.

$catalogId=trim($formValues['catalogId']); 

Next, use the PHP Oracle extension to connect with the Oracle database and determine if a Catalog table row is defined for the catalog id value input in the input form. If the result set is empty, a Catalog table row for the catalog id value is not defined in the database table. Therefore, the Catalog Id field value added in the form is valid.

Next, we shall generate a response to be sent to the client application. A response contains one or more command messages. Some of the commonly used command messages are discussed in table below.

Command Message Description
Assign Sets the specified attribute of an element in input page with method addAssign().
Append Appends data to the specified attribute of an element in the input page with method addAppend().
Prepend Prepends data to the specified attribute of an element in the input page with method addPrepend().
Replace Replaces data in the specified attribute of an element in the input page with method addReplace().
Script Runs the specified JavaScript code with method addScript().
Alert Displays an alert box with the specified message with method addAlert().

If the result set is empty display a message, "Catalog Id is Valid". The addAssign method sets the innerHTML of the validationMessage div.

$objResponse->addAssign("validationMessage","innerHTML","Catalog Id is Valid");

If the result has rows, set the innerHTML of the validationMessage div to "Catalog Id is not Valid".

$objResponse->addAssign("validationMessage","innerHTML","Catalog Id is not Valid");

Next, fetch values from the result set and set the values in the input form fields. Set the value attribute of the input form field elements with addAssign method. For example, the value attribute of the journal element is set as shown below.

$objResponse->addAssign("journal","value",$journal);

Also disable the submit button.

$objResponse->addAssign("submitForm","disabled",true);

Return the $objResponse object from the validateCatalogId function as an XML string.

return $objResponse->getXML();

Process the Ajax response

The XML response is sent to the xajax processor, which sends the XML response to the xajax’s JavaScript message pump. The message pump parses the XML instructions and sets the elements in the input page.

The data specified in the $xmlResponse object with addAssign; method is therefore set in the input form. The input.php script is available in resources zip.

Run the input.php script in the Apache web server with the URL http://localhost/input.php. Start adding a value for the Catalog Id field. An XMLHttpRequest request is sent to the server with each addition to the text field. The input page gets updated with response from the server that contains instructions about the validity of the Catalog Id. A message is displayed (below) to verify if the Catalog Id field value is valid.

Validating Input Field.

If a value is specified that is already defined in the Catalog table, a message "Catalog Id is not Valid" is displayed - as in our next screen shot.

Catalog Id not Valid.

A new catalog entry can be created by specifying a Catalog Id field that is valid and adding values to the other form fields, as shown in our final screen shot.

Catalog Id Valid.

Finally

Ajax has various applications such as auto completion, dynamic form validation, and partial page refreshes. In this article you have learned to use Ajax with PHP with a PHP framework for Ajax. You did not have to use an XMLHttpRequest object to open and send an Ajax request and process the Ajax response. Xajax generates the required JavaScript, thus, facilitating the development of an Ajax/PHP application. ®