QRdvark.com

Using Xajax in an Object Oriented Environment

By Kevin Waterson

Contents

  1. Abstract
  2. The Database
  3. Initializing Xajax
  4. Registering Functions
  5. The Object Response
  6. The HTML
  7. Putting it all together
  8. Credits

Abstract

In the previous tutorial, Introduction to Xajax the basic concepts of using xajax were layed out in simple procedural code. This tutorial takes the next step in development and shows, by way of example, how xajax can be utilized in an Object Oriented environment.

Here we describe a simple test MySQL database with a single table of employees. This table is then used to populated several HTML divs by using an employees class as the basis.

The Database

The database, as mentioned above, is named test, with a single table called employees. It looks like this.

CREATE TABLE employees (
employee_id int(11) NOT NULL AUTO_INCREMENT,
employee_firstname varchar(25) NOT NULL,
employee_surname varchar(25) NOT NULL,
employee_dept varchar(25) NOT NULL,
PRIMARY KEY (employee_id)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

INSERT INTO employees VALUES 
(1,'Simon','Brown','Janitor'),
(2,'Imran','Green','Programming'),
(3,'Troy','Blew','programmimg'),
(4,'Peter','Smith','Systems Engineering');

Initializing Xajax

To set up xajax within a class a class property needs to be declared to hold the object. Also, as this class uses PDO to conntect to a MySQL database, a class property can be set to hold the database instance also. These properties will be private, which means they can only be accessed from within the employees class.

The javascript that is generated by xajax needs to be public as it will be accessed from outside of the class itself, so a public $xajax_js variable is declared also


<?php

/**
 *
 * @class to define an animal
 *
 */
class employees
{
    
/**
     * Database and xajax properties
     */
    
private $db$xajax;

    
/**
     *The xajax generated javascript
     */
    
public $xajax_js;

With the class properties set to hold the values, the actual initialization, or instantiation of the xajax, and PDO, classes can be made in the constructor. The code will now look like this.


<?php

    
/**
     *
     * @class to define an animal
     *
     */
    
class employees
    
{
        
/**
         * Database and xajax properties
         */
        
private $db$xajax;
    
        
/**
         *The xajax generated javascript
         */
        
public $xajax_js;

        
/**
         *
         * @constructor
         *
         */
        
public function __construct()
        {
            
/*** set up the database connection ***/
            
$this->db = new PDO("mysql:host=localhost;dbname=test"'username''password');

            
/*** set up the xajax environment ***/
            
include 'xajax/xajax_core/xajax.inc.php';
    
            
/*** a new xajax object ***/
            
$this->xajax = new xajax;
        }

There is only a small difference there than to the procedural method. Stepping through the code, the database connection is made, and the resource assigned to the private $db property. Following this, is the actual xajax instantiation. In the procedural method, the xajax instance, was simply assigned to a variable named $xajax. This is much similar and is assignned to the property $xajax. Access to the xajax instance is now via $this->xajax.

Registering Functions

In the previous tutorial, the registering of functions was a simple call to the xajax register method.such as this..


<?php

$rqstButton 
$xajax->register(XAJAX_FUNCTION'showText');

?>

When within a class, the register function is still used, however, with a few changes to the parameters. Instead of simply accepting the name of a function, an array is given with three elements. Each element does the following..

  1. The name of the class method
  2. The calling class
  3. The name of the class method

With the class methods registered into $this->xajax the processRequest can be run, and the xajax javascript generated.


<?php

/*** register the xajax functions ***/
$this->xajax->register(XAJAX_FUNCTION, array('getEmployees'$this'getEmployees') );
$this->xajax->register(XAJAX_FUNCTION, array('getEmployeeData'$this'getEmployeeData') );

/*** process the request ***/
$this->xajax->processRequest();

/*** the path is relative to the web root mmmk ***/
$this->xajax_js $this->xajax->getJavascript('/xajax')

The Object Response

There is no diffence to how the object response is generated within a class, when compared to calling fromsimple function. The same basic syntax applies.


<?php
    $objResponse 
= new xajaxResponse;
    
$objResponse->assign('some_div''innerHTML''some content');
    return 
$objResponse;

So the class methods will follow the same. The class methods will look like this...


<?php
    
/**
     *
     * @Purpose Get Empoyee data from database
     *
     * @param int employee_id The ID of the employee
     *
     * @return object An xajax object response
     *
     */
    
public function getEmployeeData($employee_id)
    {
        
/*** a new xajax response object ***/
        
$objResponse = new xajaxResponse;

        
$html '<table>';
        
/*** get employee info from database ***/
        
$stmt $this->db->prepare("SELECT * FROM employees WHERE employee_id = :employee_id");
        
$stmt->bindParam(':employee_id'$employee_idPDO::PARAM_INT);
        
$stmt->execute();
        
$result $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach( 
$result as $data )
        {
            
$html .= '<tr><td>ID</td><td>'.$data['employee_id'].'</td><tr>
            <tr><td>Name</td><td>'
.$data['employee_firstname'].' '.$data['employee_surname'].'</td></tr>
            <tr><td>Department</td></td>'
.$data['employee_dept'].'</td></tr>';
        }
        
$html .= '</table>';

        
/*** assign to HTML to the innerHTML of the data_div ***/
        
$objResponse->assign('data_div''innerHTML'$html);

        
/*** return the object response ***/
        
return $objResponse;
}


    
/**
    *
    * @get the emplyees
    *
    * @return array
    *
    */
    
public function getEmployees()
    {
        
/*** a string to be returned ***/
        
$html '<select name="employees" onchange="xajax_getEmployeeData(this.value); return true;">';
        
$html .= '<option value="">Select</option>';
        
$stmt $this->db->prepare("SELECT employee_id, employee_firstname FROM employees");
        
$stmt->execute();
        foreach(
$stmt->fetchAll(PDO::FETCH_ASSOC) as $data)
        {
            
$html .= '<option value="'.$data['employee_id'].'">'.$data['employee_firstname'].'</option>';
        }
        
$html .= '</select>';
    
        
/*** a new xajax response object ***/
        
$objResponse = new xajaxResponse();

        
/*** assign the innerHTML attribute to the new $content ***/
        
$objResponse->assign("dropdown_div","innerHTML"$html);

        
/*** return the object response ***/
        
return $objResponse;
    }

The HTML

The HTML is actually just HTML, but within the document head, will be the javascript generated by the employees class. As the getJavascript method is called in the constructor, the xajax_js variable is immediately available and contains the xajax generated code that can be used directly in the HTML head.

This is done very simply but instantiating the employees class, and echo'ing the xajax_js variable.


<?php
    
/*** a new employees instance ***/
    
$employees = new employees;

    
/*** display the xajax javascript ***/
    
$xajax_js $employees->xajax_js;

    
/*** display the xajax javascript ***/
    
echo $xajax_js;
?>

Putting It All Together

With all the parts in place, the completed script looks like this...


<?php

/**
 *
 * @class to define an animal
 *
 */
class employees
{
    
/**
     * Database and xajax properties
     */
    
private $db$xajax;

    
/**
     *The xajax generated javascript
     */
    
public $xajax_js;

    
/**
     *
     * @constructor
     *
     */
    
public function __construct()
    {
        
/*** set up the database connection ***/
        
$this->db = new PDO("mysql:host=localhost;dbname=test"'username''password');

        
/*** set up the xajax environment ***/
        
include 'xajax/xajax_core/xajax.inc.php';

        
/*** a new xajax object ***/
        
$this->xajax = new xajax;

        
// $this->xajax->setFlag('debug', true);

        /*** register the xajax functions ***/
        
$this->xajax->register(XAJAX_FUNCTION, array('getEmployees'$this'getEmployees') );
        
$this->xajax->register(XAJAX_FUNCTION, array('getEmployeeData'$this'getEmployeeData') );

        
/*** process the request ***/
        
$this->xajax->processRequest();

        
/*** the path is relative to the web root mmmk ***/
        
$this->xajax_js $this->xajax->getJavascript('/xajax');
    }

    
/**
     *
     * @Purpose Get Empoyee data from database
     *
     * @param int employee_id The ID of the employee
     *
     * @return object An xajax object response
     *
     */
    
public function getEmployeeData($employee_id)
    {
        
/*** a new xajax response object ***/
        
$objResponse = new xajaxResponse;

        
$html '<table>';
        
/*** get employee info from database ***/
        
$stmt $this->db->prepare("SELECT * FROM employees WHERE employee_id = :employee_id");
        
$stmt->bindParam(':employee_id'$employee_idPDO::PARAM_INT);
        
$stmt->execute();
        
$result $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach( 
$result as $data )
        {
            
$html .= '<tr><td>ID</td><td>'.$data['employee_id'].'</td><tr>
                <tr><td>Name</td><td>'
.$data['employee_firstname'].' '.$data['employee_surname'].'</td></tr>
                <tr><td>Department</td></td>'
.$data['employee_dept'].'</td></tr>';
        }
        
$html .= '</table>';
        
        
        
$objResponse->assign('data_div''innerHTML'$html);
        return 
$objResponse;
    }


    
/**
    *
    * @get the emplyees
    *
    * @return array
    *
    */
    
public function getEmployees()
    {
        
/*** a string to be returned ***/
        
$html '<select name="employees" onchange="xajax_getEmployeeData(this.value); return true;">';
        
$html .= '<option value="">Select</option>';
        
$stmt $this->db->prepare("SELECT employee_id, employee_firstname FROM employees");
        
$stmt->execute();
        foreach(
$stmt->fetchAll(PDO::FETCH_ASSOC) as $data)
        {
            
$html .= '<option value="'.$data['employee_id'].'">'.$data['employee_firstname'].'</option>';
        }
        
$html .= '</select>';

        
/*** a new xajax response object ***/
        
$objResponse = new xajaxResponse();

        
/*** assign the innerHTML attribute to the new $content ***/
        
$objResponse->assign("dropdown_div","innerHTML"$html);

        
/*** return the object response ***/
        
return $objResponse;
    }
/*** end of employee class ***/


/*** a new employee object ***/
$employees = new employees;

/*** display the xajax javascript ***/
$xajax_js $employees->xajax_js;

?>

<html>
<body>
<head>
<title>QRdvark.com XAJAX</title>
<?php
    
/*** display the xajax javascript ***/
    
echo $xajax_js;
?>
</head>
<body>

<p id="button"><button type="button" onclick="xajax_getEmployees(); return true;">Show Employees</button></p>
<p id="dropdown_div"></p>
<div id="data_div"></div>

</body>
</html>