Basically, the problem is this:
<?php $test="foobar"; ?>
If within the html document I call
<script type="text/javascript">alert("<?php echo $test; ?>")</script>
, everything is fine.
However, if I do the same thing in an external jS document included with
<script type="text/javascript" src="foo.js"></script>
it does not work.
Is there any way to do this?
In the first case you actually pass the value to the PHP script, where
<?php echo $test; ?>is parsed by PHP parser and replaced by the value of$testPHP variable.In the second case you just include ‘
<?php echo $test; ?>‘ string into JS file and this is not parsed.My suggestion is: pass this value the way you are passing now, but properly reference it from the external JS file. For example you can invoke some function defined in JS file, passing the parameter from PHP file.
There is also the ugly way of doing that, such as making your server treat JS files as PHP files, but I am not recommending it.
Some example:
If you include in your PHP file:
and in your JS file (foo.js):
you should see
$testvalue being alerted when the script executes (assuming I did not make a mistake writing this ;)).