Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP variables in Javascript include files for view in MVC

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.

like image 991
Chad Johnson Avatar asked Jun 19 '26 16:06

Chad Johnson


2 Answers

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>
like image 72
Travis Avatar answered Jun 21 '26 07:06

Travis


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.

like image 38
Gergely Orosz Avatar answered Jun 21 '26 07:06

Gergely Orosz