Pass PHP variables to Javascript in Drupal 7 ?

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

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.

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.

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 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *