I need a controller in my Zend Framework project, which should handle only ajax requests.
My approach at the moment is to extend the Zend_Controller_Action:
The content need only be switched when you're actually calling an ajax action. I think the Zend way is a good way. It is very flexible and easy to implement. In most cases, different Controllers will have a need for a couple of ajax actions. I don't see the need or the advantage of a pure ajax controller.
Every controller can have something like this in the init():
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('some-toggle', 'html');
$ajaxContext->addActionContext('some-other-ajax-thing', 'json');
$ajaxContext->initContext();
The action looks like every other action. The view script has just one var like:
response; ?>
... and has to be called actionname.ajax.phtml.
Then, if you're pushing additional actions on your action stack, you need to do that only for non-ajax requests like so:
if (!$request->isXmlHttpRequest())
{
//push actions on stack
}
Additionally, you have to pass a format param along with the ajax post url like posturl/format/html
or posturl/format/json
.