Search code examples
jquerydrupalvariablesmoduledrupal-7

PHP variable to jQuery in Drupal 7


My issue is passing a PHP variable from my custom module to jQuery. I have successfully done this in the past in D6 but I must be missing something in D7.

The following is my module code:

  function mymodule_init(){
    $path = drupal_get_path('module', 'mymodule');

    drupal_add_js("{$path}/js/filtering.js");
    drupal_add_js(array('staff_filter' => array('path' => $path)), 'setting');

  }

And this is my jQuery code:

(function($){
    console.log( Drupal.settings.toString() );
    console.log( 'TESTING : ' + $(Drupal.settings.path).html() );
    console.log( Drupal.settings.toSource() );
})(jQuery);

And I get the following from my 3 console prints:

[object Object]
TESTING : null
({})

Solution

  • As you're adding a setting with a parent called staff_filter your settings will be available under a settings object with the same name in javascript. Your path will be here:

    Drupal.settings.staff_filter.path