What is the best way to pass a server-side PHP variable to Javascript?
To simplify the problem assume that we have a variable in PHP ($phpVar
) and we want to assign its value to a Javascript variable (jsVar
)
Javascript files are loaded in html - they are not created dynamic!
Some food for thought:
1. Print with PHP before loading Javascript files:
<script language="javascript" type="text/javascript">
var jsVar= <?php echo $phpVar?>;
</script>
2. Store in DOM (in hidden elements)
a. in PHP:
<span data-name="phpVar" data-value="<?php echo $phpVar?>"></span>
b. Read in Javascript files (assuming jQuery available):
var jsVar= $('span[data-name="phpVar"]').attr('data-value');
3. Ask it with AJAX after page has loaded
Obviosly not the best solution. Doesn't fit to all scenarios and requires an additional request...
In conclusion:
- They both seem ugly to me... Is there a better approach?
- Is there any frameworks that can handle this dependecies? Please keep server reconfiguration minimal.