HOWTO: Pass php variables to the javascript
Before starting this I'd suggest you at least walk through the HOWTO: Add a jQuery effect tutorial. This will give you some basic ground to stand on before moving forward. Additionally it would be of some benefit if you at least understood the syntax for variable_get and what it does. Docs for the various functions we will be using can be found here:
The Problem:
The problem is that we'd like to be able to create and store variables in our drupal database that the javascript ultimately uses. The problem with this is that javascript doesn't directly talk to a database, and so we need an intermediate step. Most of the time this would be done with XML in an AJAX style approach, but a typical AJAX implementation is a little bit of overkill for what we're trying to achieve. We don't want to modify the DOM, we just want to pull a variable from the variables table and use it in our javascript.
The Solution:
Drupal has some built in functions that make doing this rather easy: namely drupal_add_js & drupal_to_js.
We're going to start with the assumption that you already have a variable in your variables table named "my_variable". In your module or whatever sort of code you happen to be writing that needs this you almost certainly have a line that calls your .js file. For the purposes of this example, I'll be using a file called "my_js_file.js". $path is a variable that contains the path to my module.
<?php
drupal_add_js("var my_js_variable = " . drupal_to_js(variable_get('my_variable', '')) . ";", 'inline');
drupal_add_js("$path/my_js_file.js");
?>Drupal_add_js is doing a number of things for us here, not only is it adding our .js file to the page, but it's also allowing us to format a javascript style variable and add it inline to the page, making it available to our other javascript files. drupal_to_js is taking a variable (retrieved by variable_get) and formatting it for use in javascript. The ";" ends our line of javascript for us, and then the "inline" explicitly states that the script should be placed inline.
The resulting code should look something like this:
<script type="text/javascript" src="/sites/all/modules/my_module/my_js_file.js"></script>
<script type="text/javascript">var my_js_variable = "variable_value";</script>Hopefully this should enable you to make your modules more dynamic and enable you to start some interactions between your jQuery and the drupal database.
