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);
}
Recommended Reading : How to Log Errors in Database in CakePHP
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.
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.
var $helpers = array('Js' => 'Jquery');
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);