Unified AJAX/HTTP-requests with Zend_Layout and jquery

We use the isXmlHttpRequest() method of the request object to differ normal http from ajax requests. Then we just disable the Zend_Layout engine and the default view-helper will render the right view-script for us. If we open the /test/index the left and right actions assign the rendered views to layout variables.

Class TestController extends Zend_Controller_Action {

	public function init() {
		$this->_helper->layout()->setLayout('default');

		/**
		 * disable layouts for ajax request
		 */
		if ($this->_request->isXmlHttpRequest()) {
			$this->_helper->layout()->disableLayout();
		}
	}

	/**
	 * open /test and load left and right action
	 * as normal http request
	 */
	public function indexAction() {
		$this->leftAction();
		$this->rightAction();
	}

	public function leftAction() {

		/**
		 * if layout enabled assign content to left variable
		 * else the view helper will render left.phtml automatic
		 */
		$this->_helper->layout()->left = $this->view->render('test/left.phtml');
	}

	public function rightAction() {
		/**
		 * see left action
		 */
		$this->_helper->layout()->right = $this->view->render('test/right.phtml');
	}

}

<div id="left"><?php echo $this->layout()->left;?></div>
<div id="right"><?php echo $this->layout()->right;?></div>

<!-- render with ajax (jquery) -->
<script type="text/javascript">
	$(function(){
		$('#left').load('/test/left');
		$('#right').load('/test/right');
	});
</script>

http://akrabat.com/2007/12/11/simple-zend_layout-example/
http://framework.zend.com/wiki/display/ZFPROP/Zend_Layout

Tags: , , , ,