Using requestAction & custom layouts to add XHR functionality

By A.Doherty aka "am_d"
This tutorial outlines a method for creating or modifying Cake apps that work swiftly for XHR(XmlHTTPRequest)-enabled clients and degrade well to non-XHR/AJAX (even javascript disabled) clients. The guidance provided here will be most suitable to newly converted Bakers. It simply outlines some of Cake's many flexible features and shows how using them in combination can bring rapid returns.

We'll use the flexibility of Cake's requestAction method and some custom layouts to add XHR to your application without having to rewrite the core M's, V's or C's of your current app.


No internal Ajax Cake methods are used in this tutorial. Please consider thisefore you proceed. While you won't learn anything about those methods, you will be shown a way to turn an existing application into an XHR enabled one with a minimum of effort and with no impact upon the function of the application as it is without XHR or Javascript.


For my sanity, the tutorial does use the prototype and Mootools frameworks to provide DOM access, this is to change Cake generated links into XHR links in loaded content. You can do this any way you wish, but Mootools was used in this instance. The code samples expect a 'script src' for Mootools to be included in your default layout.


  • We'll take a simple MVC setup that displays a month-to-view calendar, with links to the previous and next month's calendars too. To keep unnecessary code to a minimum, I won't be showing the calendar, just the month and year that the calendar represents.
  • We'll then split the controllers up into smaller units so that we can gain access to them via XHR.
  • Next we'll add the one (just one!) line of code to these smaller controllers so that they will work with our XHR request, but this one line will not change their usual non-XHR function. Then we'll add an action to aggregate them all into a response for conventional usage.
  • Once our views are in place, we'll add our additional layouts to make sure we retain the XHR functionality across the MVC Calendar.

Initial Setup


First create a dummy database table for the model (this won't be used, but is necessary). Then create the following:


controllers/calendar_controller.php

Controller Class:

Download code <?php 
class CalendarController extends AppController {
 
  function 
index() {
    
  }
?>

models/calendar.php

Model Class:

Download code <?php 
class Calendar extends AppModel {
   var 
$name 'Calendar';
}
?>



views/calendar/index.thtml

View Template:

Download code
<h1>Calendar Index</h1>
 <h3>Non-XHR</h3>

Page 2: Determine the XHR Elements

Login to Submit a Comment