DEV Community

Discussion on: How to create Javascript variables from PHP variables?

Collapse
 
msamgan profile image
Mohammed Samgan Khan

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?

Collapse
 
supunkavinda profile image
Supun Kavinda

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.

<?php include_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.

<?php include_once 'js-config.php' ?>

And, js-config.php will have something like:

<?php
    phpVarsToJs(array(
         'name' => 'John',
         'age' => 23,
         // ....
    )); 
?>

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!