Drupal - how to send variable from .php file to .js file?

You should use drupal_add_js() in your module, there is no need to output the variable in your .tpl.php:

drupal_add_js(array('YOURMODULE' => array('testvar' => $testvar)), array('type' => 'setting'));

And in your JavaScript, you can the access the value in Drupal.settings.YOURMODULE.testvar:

alert(Drupal.settings.YOURMODULE.testvar);

Direct usage of global variables (as suggested in your code sample) is a discouraged practice in JavaScript as it clutter the global namespace. Also, if your code is triggered on page load, check the "Behaviors" section in Managing JavaScript in Drupal 7 documention (the whole page is worth reading).


In your MODULENAME.module file use the following code.

$testVariable = 'himanshu';
drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');

And in MODULENAME.js use the following one.

(function($) {
  Drupal.behaviors.MODULENAME = {
    attach: function (context, settings) {
      alert(settings.MODULENAME.testvar);
    }
  };

})(jQuery);

In this way, you can pass your PHP variable to JavaScript, and use it.


For Drupal 8, drupal_add_js() was removed (it was deprecated in Drupal 7 already) => see this for further information.

The way to send PHP information to Javascript is perfectly described by @4k4's answer to a similar question.

return [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#items' => $my_items,
  '#attributes' => ['class' => 'some_class'],
  '#attached' => [
    'library' => ['my_module/my_library'],
    'drupalSettings' => [
      'my_library' => [
        'some_variable1' => $value,        // <== Variables passed
        'another_variable' => $take_this,  // <== 
      ],
    ],
  ],
];

In JavaScript, they can be used as follows:

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_library = {
    attach: function (context, settings) {

      alert(drupalSettings.my_library.some_variable); //alerts the value of PHP's $value

    }
  };
})(jQuery, Drupal, drupalSettings);

Tags:

Javascript

7