AJAX Zend Framework Tips

Posted By: Tony Baird

Last Updated: Saturday November 21, 2009

I’ve been doing some work with Zend Framework in the javascript front and I figured I may as well post a bunch of the things I’ve noticed as of recently that might be useful for others.

Adding javascript files on a specific controller

What you want your layout to look like:

[php] [/php]

Here’s an example controller:

[php] class IndexController extends Zend_Controller_Action { public function init() { $this->view->headScript()->appendFile(‘path/to/my/javascript/file’); } /* Inside an action */ public function indexAction() { $this->view->headScript()->appendFile(‘path/to/my/other/javascript/file’); } } [/php]

This portion will allow you to do things where you want a javascript file on a specific controller only. Or even in some cases you want it on a specific action and it all can be handled with Zend Framework rather than customizations to your layout with special view flags you added yourself.

How to detect AJAX Requests

A lot of people are doing things like say this:

[php] if($this->_request->getQuery(‘ajax’) == 1) { // Some code $data = array(1,2,3,4); $this->_helper->json($data); } [/php]

You can actually do this instead:

[php] if ($this->getRequest()->isXmlHttpRequest()) { // Some code $data = array(1,2,3,4); $this->_helper->json($data); } [/php]

In both cases after we use the json helper which will send json data back to the users browser.  This can be really powerful where you can have the same action handle several different types of requests depending on browser capability with very little code replication.  So for example our users can turn javascript features on or off.  On the listing page action it has three different exit points.  One where it just renders a plain table for the javascript table to render.  The other is for when it’s a xml http request and the third is when the user has javascript disabled.  The last two actually use the same PHP code except for the non javascript uses a different view while the json version sends it back as json.

Ready to get started? Build your site from
$2.24/mo
GET STARTED NOW