I'm using drupal_add_js for some inline jQuery - I need to parse some php variables in the inline jQuery, what is the correct way to do it?

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)

I've tried this, and it DOES print the variable, but breaks the JS code in the process (splits the jquery code up and doesnt function) :

drupal_add_js('jQuery(document).ready(function () { alert(" '. print $site_name .' "); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  • While I don't recommend doing this particular task this way (I will comment a link showing the right way) but have you tried swapping the quotes around, like this: drupal_add_js("jQuery(document).ready(function () { alert(' " . print $site_name . " '); });", array('type' => 'inline', 'scope' => 'footer', 'weight' => 5) ); didn't have a chance to try it myself. – burnsjeremy Mar 15 '15 at 9:22
  • Here is the way forward: tylerfrankenstein.com/code/drupaladdjs-setting-example you need to add the site name var as a drupal JS setting, then on ready you can access the var in your jS script which will be in the same place you are placing the var now. This may seem redundant but later on you may need that site name again for another footer-esq script and you would have it easily. If you want me to write an example as an answer just let me know. – burnsjeremy Mar 15 '15 at 9:32

Just remove the print function from your code:

drupal_add_js('jQuery(document).ready(function () { alert(" '. $site_name .' "); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)

Looking at the javascript Window alert() Method it has this syntax:


And the message parameter has the type string

PHP's print function prints to the output buffer and returns an int. It has this definition:

int print ( string $arg )

So your code prints the variable $site_name to the output buffer and returns an int, and your string for the alert is then an integer and you have printed to the output buffer which you did not want to do.

  • YES YES YES!!! Thank you Sir! Simply removing print fixed the problem. – caustic Mar 15 '15 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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