DEV Community

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

Collapse
supunkavinda profile image
Supun Kavinda Author

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!