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:

<?php echo $this->doctype(); ?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
    	<?php echo $this->HeadMeta(); ?> 
    	<?php echo $this->headTitle(); ?> 
	<?php echo $this->headScript() ?> 
<div id="content">
    <h1><?php echo $this->escape($this->title); ?></h1>
    <?php echo $this->layout()->content; ?>

Here’s an example controller:

class IndexController extends Zend_Controller_Action
	public function init()
    	/* Inside an action */
	public function indexAction()

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:

if($this->_request->getQuery('ajax') == 1)
	// Some code
	$data = array(1,2,3,4);

You can actually do this instead:

if ($this->getRequest()->isXmlHttpRequest())
	// Some code
	$data = array(1,2,3,4);

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.

This entry was posted in PHP, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.