Home > Intermediate Scripts, Tutorials > Using Xajax in an Object Oriented Environment

Using Xajax in an Object Oriented Environment

December 30th, 2008 Leave a comment Go to comments

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_id, PDO::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_id, PDO::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>PHPRO.ORG 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>
  1. February 6th, 2009 at 23:29 | #1

    Hi, i just would love if you put examples of all the codes taht appar here, thanks

  2. April 20th, 2009 at 10:50 | #2

    Just want to thank you for your tutorial on how to use xajax in a OOP environment, I’ve been searching for days and also created few poste on xajax forum, with no luck.

    This was the last place I had to look, and if I couldn’t find a way I would just give up.

    Thanks again and great tutorials

  3. h_45h
    August 4th, 2009 at 09:22 | #3

    Very nice example. Still, do you have any idea if you can register the whole class(an instance of it, of course) through the $xajax->register() method? By doing so, you could call any method without having to register it as a function. Is this possible?

  4. d.rogkov
    October 29th, 2009 at 08:20 | #4

    Thank you very much for this post!

  5. Anthony
    February 9th, 2010 at 17:08 | #5

    Like Jagar, I was searching for 2 days for such a kind of example. You saved a part of my project from an awful solution with ugly php files everywhere. I can move on now.

    Thanks a lot.

  6. December 21st, 2010 at 07:56 | #6

    Hey i want you to give me a code and tell me how to do a search engine like this -> http://Www.ingaraj.ro <- (upper-left)

  7. Claudio Amorim
    December 30th, 2010 at 03:34 | #7

    Great tutorial. I’ve been frustrated long time because I didn’t manage to get xajax working within an object. Your tutorial is very clear, simple and understandable.
    Again, thank you a lot.

  1. No trackbacks yet.