Ketan Patel

How to Pass the Controller Data to JS File in CakePHP

Sometimes it requires to pass the data of the controller file to the javascript files or the view files in cakephp. CakePHP has one inbuilt method called “Controller::set() ”for passing the variable from controller to view. We will use this method in this tutorial.



Code Logic.

We have to create one array that can hold variable that can be used in the js or view files.we will call it as 
var $_jsvariables=array();

write the following code in your appcontroller.php


public function setjsvariables ($name, $value)
{
if (key_exists($name, $this->_jsvariables))
{
throw new Exception('a variable already has that name');
}
        $this->_jsvariables [$name] = $value;
}


public function beforeRender()
{
    // We are Setting the jsvariables array which holds the variables that will be used in js files.
    $this->set('jsVars', $this->_jsvariables);
}



Now  we will add the following code in our layout file (Example: views/layouts/default.ctp) in the head section before all the  scripts of the layout.

<?php echo $this->Html->scriptBlock('var jsVars = '.$this->Js->object($jsVars).';'); ?>
So the code written above will be loaded before any other scripts.To know about scriptblock in cakephp follow this link : http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html

Now Add js helper in your controller.

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


That’s it most of the things are done.From now if you want to set any javascript variable from the controller ,you simply have to use the method of the controller.

Example :  $this->setjsvariables('testvariable', 'Test Value');   

For accessing this variable in your js or the view file (if inline js is written in view) just type.

alert(jsVars.testvariable);

ketan patel

About Ketan Patel -

I have developed a wide range of websites using CorePHP, Opencart, CakePHP and CodeIgniter including sites for startup companies and small businesses. Apart from my blogging life, I like to read Novels, Listening music and Net surfing.

Subscribe to this Blog via Email :