Zend tip: disable all rendering in controller when serving AJAX request

NOTE: this assumes you already know a fair bit about how the Zend framework’s rendering and layout engine works.

I have a Zend Framework powered web site that I’m adding some AJAX to. Serving the AJAX request inside a controller by looking for requests with the isXmlHttpRequest flag set to TRUE is simple.
Inside the controller you then assemble whatever JSON or HTML response you have and return it, like this for example:

$this->getResponse()->setHeader('Content-Type', 'text/html')->setBody($response);

Ok, the point here is that when I did this and dutifully called setNoRender using the viewRender helper, my clean and simple response had a large chunk of HTML appended to it.
Now, I am using “response segments” in my Zend layout, i.e. I’ve got a controller action that automatically renders a part of every page, regardless of which controller is the active one. It was this controller’s rendered output that – still – was generated and appended to my neat AJAX response.

So, it turns out, that to prevent this to be rendered I had to disable all controller rendering and setNoRender doesn’t do that. It just disables rendering from within the current controller.
The code to include is instead

This works, and it is auto reset every time you reload the page.

Now my AJAX response is just what it should be.


One thought on “Zend tip: disable all rendering in controller when serving AJAX request

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s