Passing PHP values to Javascript in Joomla

In a previous blog post, I was extolling the virtues of the wp_localize_script function in WordPress as a way to pass PHP values to Javascript. It turns out that Joomla offers similar functionality.

Using a language constant to store the value, create a global Javascript array in PHP using the following syntax:

JText::script('LANGUAGE_CONSTANT');

Then, in your Javascript, you can reference that value using the following syntax:

Joomla.JText._('LANGUAGE_CONSTANT');

UPDATE: For situations beyond language strings, Joomla 3.7 introduced “optionsStorage”. I use this capability in my Petfinder module for Joomla. The PHP looks like this:

$doc = JFactory::getDocument();
// get existing options, if any
$modpfOptions = $doc->getScriptOptions( 'mod_petfinder' );
// set a variable for the stored value of rotation_degree
$rotationDegree = $this->params->get( 'rotation_degree' );
// add to the options array
$modpfOptions['polaroid'] = array( 'degree' => $rotationDegree );
// add the array to the JSON object that Joomla creates
$doc->addScriptOptions( 'mod_petfinder', $modpfOptions );

On the Javascript side, I get the value of rotation degree with the following:

var modpfOptions = Joomla.getOptions( 'mod_petfinder' );
var rotationDegree = modpfOptions.polaroid.degree;