In this tutorial, I will talk about how to handle AJAX request in a clean & simple way. Whether you use jQuery, mooTools or any other JS framework (or perhaps no framework at all) you will definitely going to love this painless solution of having an ajax view rendered without doing anything (ofcourse, after you set it up properly)
Currently I am working on some projects that require a lot of Ajax support. And while working with Zend and wanting it to blend nicely with AJAX based requests from jQUery or MooTools (or any other for that matter) I developed a very nice and easy system that makes handling these requests easier.
The Application Controller
In order to have our application clean constructed, all our controllers will extend one Application Controller (I named it Project_Application_Controller ).
Like this:
//This class goes into a folder like
//root/library/Project/Application/Controller.php
//where root is your application root.
abstract Class Project_Application_Controller extends Zend_Controller_Action
{
//code goes here
}
and
Class IndexController extends Project_Application_Controller
{
//code goes here
}
Why is this good? Because you can now add any method you want to be widely available to all controllers, which we are about to use.
The AJAX Request
In your Project Application Controller add the following code:
protected $_ajax_view = 'ajax.phtml'; //Thanks Andrei Simion for giving me this ideea public function preDispatch() { //if its an AJAX request stop here if ($this->_request->isXmlHttpRequest() || isset($_GET['ajax'])) { Zend_Controller_Action_HelperBroker::removeHelper('Layout'); $this->getHelper('ViewRenderer')->setNoRender(); return TRUE; } } public function postDispatch() { if ($this->_request->isXmlHttpRequest() || isset($_GET['ajax'])) { $this->renderScript( $this->_getAjaxView() ); } return TRUE; } protected function _setAjaxView($view) { $this->_ajax_view = $view; return TRUE; } protected function _getAjaxView() { return $this->_ajax_view; }
Basically what we are doing here is to have 1 setter and 1 getter for the ajax view. If Zend determines that the current request is an AJAX request (or the parameter ‘ajax’ from the GET params exists) it will not render the layout at all and it will render an ajax view as determined by you. You can have one ajax view by default and then add more views per your needs.
Then all you have to do in order to use this system is to call the functions as this:
//Controller code is here
$this->view->message = json_encode('my_cool_data');
//View code here from root/layouts/ajax.phtml
echo $this->message;
//Or if you want to have a custom ajax view
$this->_setAjaxView('my_cool_ajax_view.phtml');
$this->view->other_message = array('test');
//and in your root/layouts/my_cool_ajax_view.phtml
if ( TRUE === is_array($this->other_message))
{
echo 'it is array';
}
else
{
echo 'it is not an array';
}
Hope you liked it!
