Passing controller variables to your JavaScript

Posted on 27/8/08 by Felix Geisendörfer

Hey folks,

this is post #8 of my 30 day challenge. One week done, yeah!

If your application requires JavaScript in order to work than you have probably been looking for an efficient way to pass CakePHP controller variables to your scripts. I already mentioned this technique in my talk at CakeFest this year, but here is the full explanation.

Essentially we started by adding a new function to the AppController which we call 'setJson':

class AppController extends Controller{
  function setJson($one, $two = null) {
    if (!is_array($one)) {
      return $this->viewVars['jsonVars'][$one] = $two;
    }
    foreach ($one as $key => $val) {
      $this->viewVars['jsonVars'][$key] = $val;
    }
  }
}

After you added this to your AppController, you will also need this in the <head> section of your app/views/layouts/default.ctp file:

if (isset($jsonVars)) {
  echo $javascript->codeBlock('window.jsonVars = '.$javascript->object($jsonVars).';');
}

So lets say your application is all ajax / js and you want to render a couple of widgets fetched from the db, this is what you would do:

app/controllers/widgets_controller.php

class WidgetsController extends AppController{
  function index() {
    $widgets = $this->Widget->find('all');
    $this->setJson(compact('widgets'));
  }
}

app/views/webroot/js/my_include.js

$(function() {
  $.each(window.jsonVars['widgets'], function() {
    $.renderWidget(this);
  });
})

So essentially this provides you with a quick and dirty way to make your PHP arrays directly accessible in JavaScript. Often times you may want to avoid such techniques for accessibility reasons, but in other cases this is just exactly what makes sense.

Feel free to drop a comment if you like this approach or have your own solution to the problem.

HTH,
-- Felix Geisendörfer aka the_undefined

 
&nsbp;