AJAX Zend Framework Tips


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:

01 <?php echo $this->doctype(); ?>
02 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
03 <head>
04 <?php echo $this->HeadMeta(); ?>
05 <?php echo $this->headTitle(); ?>
06 <?php echo $this->headScript() ?>
07 </head>
08 <body>
09 <div id="content">
10 <h1><?php echo $this->escape($this->title); ?></h1>
11 <?php echo $this->layout()->content; ?>
12 </div>
13 </body>
14 </html>

Here’s an example controller:

01 class IndexController extends Zend_Controller_Action
02 {
03 public function init()
04 {
05 $this->view->headScript()->appendFile('path/to/my/javascript/file');
06 }
07 /* Inside an action */
08 public function indexAction()
09 {
10 $this->view->headScript()->appendFile('path/to/my/other/javascript/file');
11 }
12 }

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:

1 if($this->_request->getQuery('ajax') == 1)
2 {
3 // Some code
4 $data = array(1,2,3,4);
5 $this->_helper->json($data);</pre>
6 }

You can actually do this instead:

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

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.

From http://blog.hawkhost.com/2009/11/21/ajax-zend-framework-tips/

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s