How do I pass a PHP variable to Drupal.settings global javascript? Javascript works fine, but i need to get my_var variable from module. At the moment its not working.

Clear my page cache and browser cache several times.

The variable 'my_var' is showing value on front end but not on backend/admin side.

Front end theme is Bartik; the admin theme is Seven.

All other variables are available on Admin side from Drupal.settings, except the one I pass from my custom module.

This works well on both themes.

alert(Drupal.settings.basePath);


This is my code.

MY_MODULE.module

/**
 * Implements hook_page_build().
 */
function MY_MODULE_page_build(&amp;$page) {
    ctools_include('modal');
    ctools_modal_add_js();

    // HERE it is calling the js
    drupal_add_js(array('MY_MODULE' =&gt; array('my_var' =&gt; 'MY_VALUE'),), 'setting');
    drupal_add_js(drupal_get_path('module', 'MY_MODULE') . '/js/MY_MODULE.js');
}


MY_MODULE.js

(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context) {
        alert("test");
        alert(Drupal.settings.MY_MODULE.my_var);
    }
  }
})(jQuery);


On front end, it alerts with test followed by MY_VALUE, but on admin side, it shows test; Firebug then shows me:


  Uncaught TypeError: Cannot read property 'my_var' of undefined 


How can I fix this?
calling drupal_add_js in hook_init is a fairly standard response to this kind of question, as is hook_boot.

hook_init is used for setting up things required by the page - but doesnt run on cached pages.

hook boot is used for code that has to run on cached pages as well as uncached pages.

The way I usually debug this kind of thing is with the javascript console. In chrome, open the console and type 

Drupal.settings


hit enter and it should print out the whole settings object for you to inspect. This will let you see what you have. 

I suspect the problem may be down to when hook_page_build gets fired on admin pages if Im reading your question correctly. 

Uncaught TypeError: Cannot read property 'my_var' of undefined 


means that 

Drupal.settings.MY_MODULE


evaluates to undefined. It could be at any level. 
so try the javascript console trick and see what you find (is Drupal there.. is drupal.settings there). 

you could also try

(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context,settings) {
    alert("test");
    alert(settings.MY_MODULE.my_var);
   }   
  }
})(jQuery);


which is more keeping with how it is documented for behaviours on drupal.org