Expose server side data from your module for client side javascript use

Expose server side data from your module for client side javascript use

Adding the following code in any PHP area in Drupal will give you settings values available client-side that you can use when writing JavaScript code. Pass a key/value associative array to drupal_add_js() and give it type value of 'setting'. Note that I am using an array of arrays with the key of the first array as the name of the module. This is to namespace the settings. This will keep your settings from overriding others and others from overriding yours. //PHP code in your module or in a PHP snippet anywhere on your site $jquery_settings = array( 'myModule' => array( 'mySetting1' => 'myvalue1', 'mySetting2' => 'myvalue2' ) ); drupal_add_js($jquery_settings, 'setting'); Now, within your JavaScript you can access these settings that you defined server-side /** * My JavaScript File */ alert(Drupal.settings.myModule.mySetting1); // displays myvalue1

Related Posts

Creating Related Content Blocks: Side-by-side comparison of Blocks via Views vs Content Panes via Panels

Kristin Brinner
Read more

A Simple Entity Data API for Module Builders

Tom McCracken
Read more

DrupalCon Day 2: "Drupal Side of the Moon"

Tabatha Patterson
Read more

Stop Spam, Not Your User - The un.captcha.lous Module Demo

Michael Kasberg
Read more

Drupal Importing Nodes with the Feeds Module

Chris Sloan
Read more

Create a high performance Drupal server for just $30 a month

Randall Knutson
Read more