Passing PHP variables to non-native JavaScript -


basically, problem this:

<?php $test="foobar"; ?> 

if within html document call

<script type="text/javascript">alert("<?php echo $test; ?>")</script>

, fine.

however, if same thing in external js document included

<script type="text/javascript" src="foo.js"></script>  

it not work.

is there way this?

in first case pass value php script, <?php echo $test; ?> parsed php parser , replaced value of $test php variable.

in second case include '<?php echo $test; ?>' string js file , not parsed.

my suggestion is: pass value way passing now, reference external js file. example can invoke function defined in js file, passing parameter php file.

there ugly way of doing that, such making server treat js files php files, not recommending it.

some example:

if include in php file:

<script type="text/javascript" src="foo.js"></script> <script type="text/javascript">myhappyfunction("<?php echo $test; ?>")</script> 

and in js file (foo.js):

(function(){     var myhappyfunction = function(myparameter){         alert(myparameter);     };     window['myhappyfunction'] = myhappyfunction; // pass outside scope })(); 

you should see $test value being alerted when script executes (assuming did not make mistake writing ;)).


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -