Make php varibles visible in jquery files

Public

This is can be useful to send site base url in modules jquery files.

</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_init()
  3.  */
  4.  
  5. function modulename_init() {
  6. global $base_url;
  7. drupal_add_js(array('base_url' => $base_url), array('type' => 'setting'));
  8. }
  9. // then your jquery file in your module will look like
  10. (function ($, Drupal, window, document, undefined) {
  11.  
  12. $(function(){
  13. // this way you can dynamically get your php variables visible in your js files
  14. // so here we are getting the bas url for our site.
  15. var base_url = Drupal.settings.base_url;
  16. });
  17.  
  18. })(jQuery, Drupal, this, this.document);

Comments

fadehelix's picture

I think that better way is to use Drupal.behaviors in javascript file: http://stackoverflow.com/questions/3941426/drupal-behaviours

  1. (function ($) {
  2. Drupal.behaviors.yourModule = {
  3. attach: function (context, settings) {
  4. var base_url = settings.base_url;
  5. $('.example', context).click(function () {
  6. $(this).next('ul').toggle('show');
  7. });
  8. }
  9. };
  10. })(jQuery);

Other resources:
http://drupal.org/node/756722
http://drupal.org/update/modules/6/7#local_settings_behaviors

ooops's picture

Yes
Thanks @fadehelix