Zend Framework and jQuery

Zend Framework is a very robust PHP Framework. Using jQuery (and most other Ajax Frameworks) can be used with Zend Framework in a variety of ways. In this post, I will discuss the two most common ways that I use jQuery with Zend Framework.

Return JSON Result

Probably the most common way to that I used jQuery with Zend Framework is when I want to return a json object.

In this first example, I use jQuery’s $.ajax method to post a form and return a json object.

?View Code JAVASCRIPT
function doProfileSheetSearch() {
	$('#profileDefResults').html('');
	$('#btnProfileDefsSearch').attr('disabled', 'disabled');
	$.ajax({
		url: '/application/profilesheetdefs/getprofiledefs',
		type: 'POST',
		dataType:'json',
		data: $('#frmProfileDefsSearch').serialize(),
		success: function(data) {
			var dl = $('<dl></dl>').appendTo('#profileDefResults');
			if (data.length == 0) {
				$(dl).append($('<dt></dt>').html('No Records Found'))
			} else {
				$.each(data, function (i, itm) {
					$(dl).append(
						$('<dt></dt>').html(itm.FIELDNAME),
						$('<dd></dd>').html(itm.DESCRIPTION)
					)
				});
			}
			$('#btnProfileDefsSearch').attr('disabled', '');
		}
	});
}

The important option to note is the url option. Zend’s application files are located under the root directory (‘/application’). I’m calling a Zend Controller named profilesheetdefs (ProfileSheetsDefsController.php). And I am calling the getprofiledefsAction method with the controller. Notice that ‘action’ is not append to the end of the method call – this is not a typo. Zend knows that when I use the url ‘/application/profilesheetdefs/getProfileDefs’ that I am calling the getprofiledefsAction method.

public function getprofiledefsAction()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender();
 
    $request = $this->getRequest();
    if ($request->isPost()) {
    	$mapper  = new Model_ProfileSheetDefsMapper();
    	echo(Zend_Json::encode($mapper->fetchAll($request)));
    }
}

Whenever you want to return a json object (or any other data type that is returned ajaxally) from Zend Framework, make sure that you disable the layout and view. By default, Zend expects a controller method to have an associated view and will try to display the view.

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

Note: To send a get request, you can just append the parameters to the end of the url:

?View Code JAVASCRIPT
$.getJSON('/application/profilesheetdefs/getprofiledefs/?param1=what&param2=ever', function(data) {
 
});

or you can use the data option:

?View Code JAVASCRIPT
$.getJSON('/application/profilesheetdefs/getprofiledefs', 'param1=what&param2=ever', function(data) {
 
});

AjaxContext

In a current project, we are creating a multi-step order process. There are multiple developers on the project and each have been assigned a page (or step). The pages will be retrieved ajaxally. While trying to decide on a divide-and-conquer strategy, I came across Zend Framework’s AjaxContext action helper.

First, set up the AjaxContext in the init method of the controller.

public function init()
{
      $ajaxContext = $this->_helper->getHelper('AjaxContext');
      $ajaxContext->addActionContext('buynowqualerror', 'html')->initContext();
}

If you have multiple methods that will use the AjaxContext:

public function init()
{
      $ajaxContext = $this->_helper->getHelper('AjaxContext');
      $ajaxContext
 		->addActionContext('buynowqualerror', 'html')
		->addActionContext('buynowbasic', 'html')
		->addActionContext('buynowcontactinfo', 'html')
		->addActionContext('buynowaddtionalinfo', 'html')
		->addActionContext('buynowterms', 'html')
		->addActionContext('buynoworder', 'html')
		->addActionContext('buynowordersummary', 'html')
		->addActionContext('buynoworderconf', 'html')
 		->initContext();
}

The addActionContext method takes two parameters: the action (controller method) and the context (html, json, xml, etc).

The controller method is written just like any other controller method:

public function buynowqualerrorAction() {
      $request = $this->getRequest();
      $id = $request->getParam('product_id');
      $mapper  = new Model_Provisioning_ErrorTemplateMapper();
      $this->view->error = $mapper->getQualificationError($id);
}

The trick is in the view. You will create two views. Your primary view will just call the Ajax view.

// /application/views/scripts/provisioning/buynowqualerror.phtml
include('buynowqualerror.ajax.phtml');

And the Ajax view file should be named .ajax.phtml. This file will contain the code that you would ordinarily place in the primary view.

// /application/views/scripts/provisioning/buynowqualerror.ajax.phtml
print '<h3>Error</h3>';
print '<p>'. $this->error . '</p>';

Now in jQuery, will just load the html file that is returned:

?View Code JAVASCRIPT
$('#provisioning-buy-now-container').load('/application/provisioning/buynowqualerror/format/html');

I am loading the content from the result of the call in provisioning-buy-now-container. Notice the ‘/format/html’ appended to the end of the url. This parameter tells Zend Framework to send html content back. Remember the init method:

$ajaxContext->addActionContext('buynowqualerror', 'html')->initContext();

If I wanted to return xml, I would first change the AjaxContext:

$ajaxContext->addActionContext('buynowqualerror', 'xml')->initContext();

And the jQuery call would be:

?View Code JAVASCRIPT
$('#provisioning-buy-now-container').load('/application/provisioning/buynowqualerror/format/xml');

Now it took me a few minutes to figure out how to send parameters to the Zend controller method. But it was quite simple:

?View Code JAVASCRIPT
jQuery('#provisioning-buy-now-container').load('/application/provisioning/buynowqualerror/product_id/123/format/html');

I’m sending the parameter product_id (value: 123).

And in the controller method:

$request = $this->getRequest();
$id = $request->getParam('product_id');

That’s it. As you can see, using Zend Framework and jQuery is quite straightforward. Enjoy.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks