I need to pass a php var to a jQuery script. They are in separate files, one file to php code and another file to jQuery scripts. Is there a way of doing it? I am using Joomla 3.4.1. I just need to get Joomla version in the jQuery script.
Javascript have global variables : http://www.w3schools.com/js/js_scope.asp
inside you php file you call: JFactory::getDocument(); and you can now add some javascript at the current page with addScriptDeclaration()
In this example, we declare a myJoomlaVersion variable
<$php
$jdocument = JFactory::getDocument();
$jversion = new JVersion();
$short = $jversion->getShortVersion();
// Add Javascript
$jdocument->addScriptDeclaration(' var myJoomlaVersion = '.$short ); ?>
More info about "Inserting inline scripts from within a PHP file" https://docs.joomla.org/J3.x:Adding_JavaScript_and_CSS_to_the_page
Now you can use this variable into your javascript.
-
Thank you for your help. I'm getting the following
SyntaxError: expected expression, got '<'
– n.h. Jun 24 '15 at 14:53 -
I have edited my code. A small type on it This new one should work better – Pierre-André Vullioud Jun 25 '15 at 14:45
After this question was originally answered, Joomla introduced in version 3.5 another way of passing variables to javascript, using the addScriptOptions()
method of the Joomla Document
class. So I'm just adding this to make other people who are interested in this question aware of this alternative.
In your php file you can write eg:
$phpvars = array('alpha' => 1, 'beta' => 'test', 'gamma' => null);
$document = JFactory::getDocument();
$document->addScriptOptions('myvars', $phpvars);
Then in your javascript you can retrieve the values using:
var jsvars = Joomla.getOptions('myvars');
console.log(jsvars);
which will output on the browser console the Javscript Object structure:
{alpha: 1, beta: "test", gamma: null}
You can obviously use this multiple times in your code, using different keys (the key being 'myvars'
in the example above).
-
2Though this is a more recent addition to Joomla than the original answer, this is the correct answer for any modern Joomla component – user101289 Jan 5 '20 at 20:45
You can achieve this with the use of a global function.
So, in your JS file, you would do something like this:
<script>
var myFunction;
jQuery(document).ready(function($){
myFunction = function(version)
{
console.log(version);
// You have the version here
}
});
</script>
Then, in your default.php, you can get the Joomla version and call the function like so:
<?php
$jversion = new JVersion();
$short = $jversion->getShortVersion();
?>
<script>
jQuery(document).ready(function($){
myFunction('<?php echo $short; ?>');
});
</script>
Hope this helps