Why you need to pass php variables to javascript in drupal 7?
In some of your D7 applications you may need to access certain variables in JavaScript globally. For example we need the Base URL (stored in PHP) to be available to javascript. In Core PHP
we will do as follows
<?php $base_url = "http://yoursitename.com"; ?> ...
<script language="javascript" type="text/javascript"> var url = "My Site URL <?php echo $base_url ?>."; document.write(url); </script>
But we can pass PHP variables to javascript in drupal 7 in a much better and clean way without overwriting or including any common files.
How to pass PHP variables to Javascript in Drupal 7 ?
If you want to use common javascript variable across your application, you can do it in your custom module. In hook_init method you can initialize something which is necessary for the module or application.
Whenever a module is enabled the hook_init method will be executed first, thus all the initialization stuffs are written here.
/** * Implements hook_init(); */ function customModuleName_init() { drupal_add_js(array( 'customModuleName' => array( 'customKey' => 'customValue' )), 'setting'); }
By using this hook init method implementation we can tell Drupal application to add this PHP variable called “customKey” from your module name “customModuleName” with value of the “customKey” as “customValue” to javascript “setting” group, so that it can be accessible by javascript across your Drupal 7 application.
How to get assigned Javascript variables in your View ?
In your view or template file of themes or modules you can access this “customModuleName” key-value pair from the Javascript as shown below.
<script type="text/javascript"> alert(Drupal.settings.customModuleName.customKey); </script>
Note: The module should be enabled then only this hook_init module will be triggered and variable will be passed from PHP to javascript.
Hope this article will help you to understand how to pass PHP variables to Javascript in Drupal 7 Image may be NSFW.
Clik here to view.
The post Pass PHP variables to Javascript in Drupal 7 ? appeared first on Mydons.