1

This question already has an answer here:

Can somebody help me with this problem. In the body of a Basic page:

drupal_add_js(array('my_var' => array('orderid' => '123')), 'setting');
drupal_add_js('sites/all/scripts/printout.js');

In printout.js:

alert("Before");
alert(Drupal.settings.my_var.orderid);

Result: "Before" was alerted then returned to Basic page, no orderid. What have I done wrong?

marked as duplicate by Chapabu, AjitS, Letharion, mpdonadio Feb 13 '13 at 16:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Did you add the jQuery namespace wrappers in printout.js? – David Thomas Feb 13 '13 at 10:23
4

Make sure you call for jquery setting inside Drupal behaviour, you can do like this:

(function ($) {
    Drupal.behaviors.example_name = {
        attach: function(context) {
            alert(Drupal.settings.my_var.orderid);
        }
    }
})(jQuery);

or you can call inside jQuery's .ready() event (less preferable than behaviours approach in Drupal world):

jQuery(document).ready(function($) {
   alert(Drupal.settings.my_var.orderid);
});

These both approaches ensure that jQuery is loaded before calling a variable.

P.S. I recommend using console.log instead of alert for quick debugging, like this:

console.log(Drupal.settings.my_var.orderid);

Then go to your developer console / firebug (depending on browser you use) and you'll see an output in console.

  • Thanks Tim, it works. Didn't realize have to use jquery to get Drupal.settings vars. – user2067600 Feb 17 '13 at 2:44
  • you're welcome :) don't forget to mark this answer as "the answer" :) – Tim Feb 17 '13 at 9:52
-1

You have to say drupal where to put the javascript like this:

$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end     of   the document
);

drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

But like i learned a more sophisticated way would be to use Drupal.behaviors.

Look at my question: How to pass values from php to javascript properly?

Not the answer you're looking for? Browse other questions tagged or ask your own question.