Reputation: 10249
In my code, I use JavaScript for UI and PHP for back end. I also use PHP to store application settings and sometimes my UI code needs to access this information. My configuration file looks something like this (config.php):
$resolution_x = 1920;
$resolution_y = 1080;
etc...
When I need to access any of these settings form JavaScript, i simply use
<?php echo ... ?>
to substitute the value directly, but it just doesn't strike me as very robust.
Are they any dangers of doing this that I am not aware of? Is there a better way of doing this?
Thank you,
Upvotes: 0
Views: 375
Reputation: 2730
Echoing the variables one by one gets tedious if you need to add a lot of options. There already was a better solution suggested that uses an array and an include, but there's also the possibility of creating an object in the backend that has a method which fetches the configuration as an array.
You could then get the configuration in JS by echoing the result of calling that method in the HTML/view-file with PHP like in the previous solutions, or by calling that method with an additional HTTP request from JS which would incur the additional overhead but, if needed, also introduce lazy loading the configuration, which might be beneficial if most of the JavaScript doesn't need the configuration:
PHP
class Configuration { public static function getAll() { return file_get_contents('config.php'); } } class ConfigController { public function getConfigAction() { $config = Configuration::getAll(); return json_encode($config); } }
JS
function getConfig() { /* * Send an HTTP request to the ConfigController's getConfigAction in your * favorite manner here. */ } var config = getConfig(configUri);
Upvotes: 1
Reputation: 134207
Perhaps this is what you are already doing, but you can echo
the configuration value into a variable in your javascript. IE: var Resolution_X = <?php echo $resolution_x; ?>;
Upvotes: 1
Reputation: 5240
Is this what you are looking for?
<script type="text/javascript">
var resolution_x = <?php echo $resultion_x; ?>;
</script>
I think this is the most robust way, unless you want to find out the resolution by yourself with JavaScript.
You can make it more advanced like this:
config.php
<?php
$congig = array(
'resolution_x' => 1024,
'resolution_y' => 768
);
?>
index.php
<?php
include('config.php');
?>
<script type="text/javascript">
var config = <?php echo json_encode($config); ?>;
alert(config.resolution_x);
</script>
Upvotes: 3