I think you are talking about adding some PHP variables into a Javascript file. For example, you need index.js to have some dynamic variables to be set with PHP.
If it is what you meant, you can include the js file and the JS file should contain PHP in it.
<?phpinclude_once'index.js';?>
This will execute the PHP code in it and echo the contents to the current PHP file. But, having PHP code inside a Javascript file is a mess, in my opinion.
If you need to use this approach, I would recommend adding those dynamic variables into your PHP file. You can use an include for this. Here's how I do that.
nice article, but this will only work if we are using JS in the same PHP file. What if we include the js from some other file?
I think you are talking about adding some PHP variables into a Javascript file. For example, you need
index.js
to have some dynamic variables to be set with PHP.If it is what you meant, you can include the js file and the JS file should contain PHP in it.
This will execute the PHP code in it and echo the contents to the current PHP file. But, having PHP code inside a Javascript file is a mess, in my opinion.
If you need to use this approach, I would recommend adding those dynamic variables into your PHP file. You can use an include for this. Here's how I do that.
And, js-config.php will have something like:
If you don't need the Javascript variables (or JSON data) on the page load, the best way is to fetch the data from the server using AJAX.
Thanks!