1

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?

1
  • Did you add the jQuery namespace wrappers in printout.js? Commented Feb 13, 2013 at 10:23

2 Answers 2

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.

2
  • Thanks Tim, it works. Didn't realize have to use jquery to get Drupal.settings vars. Commented Feb 17, 2013 at 2:44
  • you're welcome :) don't forget to mark this answer as "the answer" :) Commented Feb 17, 2013 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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.