Apr 17 2008

Zend Frameworks Ajax Controller

This is a kind of quick and dirty approach to making an ajax responder in Zend Frameworks. The more elegant solution would be to make a controller plugin to add support for auth, and acl, but so far it looks like this approach works just fine for simple things.

<?php
class AjaxController extends Zend_Controller_Action {
	private $ajax_output;

	function init() {
		if($this->_request->isXmlHttpRequest()) {
			//The request was made with JS XmlHttpRequest
			$this->_helper->viewRenderer->setNoRender();
			$this->_helper->viewRenderer->setNoController();
		} else $this->_redirect('index');
	}

	public function indexAction() {
		Zend_Loader::loadClass('Zend_Json');
		$myArray = array('someData',
             			'moreData' => array(
                             			'hello'
                           			)
           	);

		$this->ajax_output = Zend_Json::encode($myArray);
	}

	function postDispatch() {
		echo $this->ajax_output;
	}
}