Don Jones
Don Jones

Reputation: 9497

How do you make Zend Framework NOT render a view/layout when sending an AJAX response?

Zend's documentation isn't really clear on this.

The problem is that, by default, Zend automatically renders a view at the end of each controller action. If you're using a layout - and why wouldn't you? - it also renders that. This is fine for normal Web pages, but when you're sending an AJAX response you don't want all that. How do you prevent Zend from auto-rendering on an action-by-action basis?

Upvotes: 42

Views: 38706

Answers (3)

midan888
midan888

Reputation: 179

Or you could simply put die() function at the end of the action

public function someAction()
{
    echo json_encode($data);
    die();
}

Upvotes: -3

Valeriy Selitskiy
Valeriy Selitskiy

Reputation: 386

If your AJAX is returning JSON you can use JSON action helper:

$this->_helper->json($data);

This helper will json_encode your $data, output it with JSON headers and die at last, so we getting clean JSON returned from action without layout and view rendering.

f.e. I am using this construction in action beginning to avoid multiple ACL checks for different actions just-for-ajax

public function photosAction() {

if ($this->getRequest()->getQuery('ajax') == 1 || $this->getRequest()->isXmlHttpRequest()) {
    $params = $this->getRequest()->getParams();
    $result = false;

     switch ($params['act']) {
        case 'deleteImage':
           //deleting something
           ...
           $result = true; //ok
           break;

        default :
           $result = array('error' => 'Invalid action: ' . $params['act']);
           break;
      }

    $this->_helper->json($result);
}

// regular action code here
...
}

Upvotes: 19

Don Jones
Don Jones

Reputation: 9497

Call this code from within whatever Action(s) is/are going to be sending AJAX responses:

$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(TRUE);

This disables the Layout engine for that action, and it turns off automatic view rendering for that action. You can then just "echo" whatever you want your AJAX output to be, without worrying about the normal view/layout stuff getting sent along for the ride.

Upvotes: 94

Related Questions