Is it possible to load views with ajax in the zend framework, that way the layout page doesn't get refreshed, just the main content div?
2 Answers
use Ajax context switching you can do it by adding this to your init function in your controller
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('my', 'html') //my is your action
->initContext();
}
The html parameter is the type of Ajax request. it can also be JSON or XML
public function myAction() {
// get what you are sending to your view : data
$this->view->data = $data;
}
create a view my.ajax.phtml to which which myAction will attempt to render to it by default
and then include my.ajax.phtml in your view (your main content div)
Comments
With Zend 1.12 we used the Zend_Controller_Action_Helper_Json;
Controller:
use Zend_Controller_Action_Helper_Json;
class MyController extends Zend_Controller_Action {
public function init() {
Zend_Controller_Action_HelperBroker::addHelper(new Zend_Controller_Action_Helper_Json());
}
public function fooAction() {
$this->getResponse()->setHttpResponseCode(200);
$this->_helper->json(array('value' => 1));
}
}
View:
- No view file
Output:
{"value":1}
Call:
http://example/my/foo