print Tutorial 3: Adding Ajax controls to a controller

Enabling xaJax

As previously mentioned xaJax is disabled by default, however a property exists within the mvcControllerBase to hold an instance of the main xaJax object. In larger projects, a custom mvcController would implement the instantiation of xaJax (similar to the admin system), but for this simple example, we will directly enable it in our guestbook controller.

To enable xajax, find the initialise() method within the guestbookController; then add below the parent call the following line:

$this->setXajax(new xajax($this->buildUriPath(self::AJAX_REQUEST_URI)));
$this->addAjaxControls();

This creates and sets the xajax object to handle the ajax requests. The requests are sent to a specific URI path that ends with the constant mvcControllerBase::AJAX_REQUEST_URI. This is handle by the base distributor that is already configured to handle this alternative URIs.

Next we need to inform xajax about the functions that are available to the webpage. This is done by overloading the addAjaxControls() method from mvcControllerBase. For this tutorial we will only add a single function, but you can add as many as you like. It is not recommended to add the entire object, otherwise you may expose methods that should not be executable.

The method we will expose will be a method to generate a random comment from the guestbook:

/**
 * Adds ajax controls to controller
 *
 * @return void
 */
function addAjaxControls() {
	$this->getXajax()->register(XAJAX_FUNCTION, array('randomComment', &$this, 'randomComment'));
}

Next we need to create our method and handle the request.