Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email: hello@sanisoft.com

Blog

[CakePHP] Passing data from controller to javascript files

These days javascript is becoming the indispensable tool for a web developer. Each and every web application uses javascript for one or the other purpose.

While working with CakePHP based projects, we need to pass variables from PHP (controller) to javascript a lot of times. To pass a variable from controller to view, Controller::set() method comes built in. Let’s try to come up with our own method to set js variables on similar lines.

Add the following code in your app_controller.php

Next, add the following code in the head section of your layout (views/layouts/default.ctp). Make sure it is added before $scripts_for_layout.

That is all it requires and we are all set to start using the newly added feature. Whenever you want to set a js variable from you controller, you can use setJsVar() controller method as shown below.

And then in your js files (or js in view if writing inline js) you can access that variable like this.

The beauty of this very simple approach is that you can set variable of any data type. Be it string, integer, boolean or an array.

Happy Javascripting 🙂

About the Author

Abbas Ali is a Mechanical Engineer by education. He turned to programming and took it as a profession just after finishing his studies. He is fascinated equally by both machines and computers.

He leads the team of dynamic programmers at SANIsoft and works as a Technology Manager. He is also an active developer on the Coppermine Picture Gallery team.

3 comments

  1. Pingback: [CakePHP] Sending JSON data in response to a controller action at SANIsoft – PHP for E Biz

  2. Hi

    Thanks for this example! Works like a charm.
    I’d just like to correct one more thing: if someone gets the error:

    Notice (8): Undefined property: View::$Js

    then add the JS helper to your controller:

    var $helpers = array('Js' => 'Jquery');

  3. Hi,

    Thanks for the trick !

    Additionally, i check if the variable already exists in the array :

    public function setJsVar($name, $value)
    {
    if (key_exists($name, $_jsVars))
    {
    throw new Exception(‘Be careful, a variable already has that name : “‘ . $name . ‘” !’);
    }

    $_jsVars[$name] = $value;
    }

Leave a Reply