Suppose I am using an MVC framework, and my views require Javascript files located in a file external to the view. My javascript located in the external file depends, however, upon a few PHP variables in my view. If I were to include the Javascript in a tag inside my HTML view, I could simply inject the PHP variables into the Javascript.
I know I can create hidden input fields and assign the variables I need as their values. Is there another, more elegant way?
I know I could probably get away with naming the .js file to .php, but I'm not too fond of doing that.
I'm not sure I understand your question completely, but if I have the gist right, couldn't you just set global javascript variables inside a script tag in the view, that would then be passed to your external js?
<script type="text/javascript">
var myvar1 = <?=$myvar1 ?>;
var myvar2 = "<?=$myvar2 ?>";
</script>
<script type="text/javascript" src="myexternaljs.js"></script>
You could make a call from JS to the server (e.g. REST) to get the variables you depend on. You would have to create a service for this but the structure would remain clean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With