How to pass values from Controller to javascript file in Cakephp


Posted on 05 Feb 16 by Vickey

These days javascript is the essential tool for an internet developer. Every and each internet application uses javascript. Sometimes we need dynamic values from database in js file. For example alert the logedin usename. In simple way we can do this by using the below code

var jsvariable='<?php echo $phpvariable; ?>';

but if you are using cakephp then there is a best way to do this task. In appController.php write the below code

public $helpers = array('Js' => 'Jquery');
public $javascriptVar=array();

public function setJavascriptVariable ($variableName, $variableValue)
	if (key_exists($variableName, $this->javascriptVar))
	throw new Exception('a variable already has that name');
	$this->javascriptVar [$variableName] = $variableValue;

public function beforeRender()
    $this->set('javascriptVariable', $this->javascriptVar);

And now by calling the function 'setJavascriptVariable' set javascript values in your controller.

public function welcomePage() {

	$this->setJavascriptVariable('myvar', 'Hi');


Now open your layout.ctp file and write the below code

echo $this->Html->scriptBlock('var javascriptVariable = '.$this->Js->object($javascriptVariable).';');

You have done now you can access this variable in every js file



If this post help you reduce time to develop, you can help me to maintain this website :)