Tuesday, June 1, 2010

Using ajax or another layout

Sometimes we want to render a view with the ajax layout, but only when it is been showed because an ajax request. I used to make two different views, and some times two different actions. But I realized that there is a component that help us tell when the call comes from an ajax request.

The component is the RequestHandler, to use it you have to set it on the controller, like this:
class ExamplesController extends AppController{
   var $components = array('RequestHandler');
and in the action we want to tell if it is an ajax call we have to set:
function myaction(){
   $this->layout = $this->RequestHandler->isAjax()?'ajax':'default';
so if it is an AJAX call the layaout that will be used is the ajax layout. By the way, this is a layout that comes with CakePHP, you don't need to create it. And you also can use any other layout you create.

No comments:

Post a Comment