How can I stop Layout rendering, when sending request through AJAX.. The problem I face is json data is echoed on the browser, not passed to tha call back function of jquery
here's my script
jQuery.ajax({
url: "/getPrivileges",
type: "POST",
dataType: 'JSON',
success: function(privileges){
alert('hellooo');
buildTree(privileges,".privBox h2");
if($(".privPrivilege"))
$("#loading").css("visibility","hidden");
},
error: function (request, status, error) {
alert('Error'+request.responseText);
}
});
and here's the routing
resources.router.routes.privilege.route = /getPrivileges
resources.router.routes.privilege.defaults.module = privileges
resources.router.routes.privilege.defaults.controller = privilege
resources.router.routes.privilege.defaults.action = get-privileges
and here's my controller
public function getPrivilegesAction() {
if ($this->getRequest()->isXmlHttpRequest()) {
...........
...........
$this->_helper->json($appPrivArray);
$this->_helper->viewRenderer->setNoRender(TRUE);
$this->_helper->layout->disableLayout();
$response = $this->getResponse();
$response->setHeader('Content-type', 'application/json', true);
}
}
First I face that layout still rendered but now the json is printed on the screen, even I don't have get-privileges.phtml view page.
and in the init() method of the controller, I make like this
public function init() {
$ajaxContextSwitch = Zend_Controller_Action_HelperBroker::getStaticHelper('AjaxContext');
$ajaxContextSwitch->setDefaultContext('json');
$ajaxContextSwitch->addActionContext('getPrivileges', 'json');
$ajaxContextSwitch->initContext();
}
how can I make response deliver to the call back function of jquery! It's important to mention that not all urls has custom routes..
please help, because I almost will retire from development using Zend framework !!
In the action, you just need to use
$this->_helper->json($appPrivArray)
You do not need to use setNoRender or anything else.
And in the Javascript you do not need to use dataType: 'JSON',
I tested this, should work fine.
JSON data is returned to jQuery (or any other library) by being "echoed on the browser". That is how the callback receives the data.
The JSON view helper disables the layout for you, as well as sets the Content-Type header to application/json so you shouldn't have to do that.
You can continue to use setNoRender(true) if you don't have a view script for the given action.
I think that this code should work fine:
public function getPrivilegesAction() {
if ($this->getRequest()->isXmlHttpRequest()) {
$this->_helper->viewRenderer->setNoRender(TRUE);
$this->_helper->json($appPrivArray);
}
}
Are you receiving any Javascript errors or does the alert('hello') not run?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With