Tags

, ,

pass-data-from-php-to-javaScriptDoes data-passing from your PHP code to JavaScript, create any problem in Drupal?

Don’t worry! Drupal provides an easy way to do this using Drupal.settings.

Now first of all what is this Drupal.settings ?
Actually Drupal.settings is an object, defined in Drupal Core. It is declared and initialized at the very beginning of JavaScript code in Drupal core along with 4 properties, among which ‘settings’ is one of them. This object contains all the Drupal core properties which can be used and extended by other modules.

Now question is how we can pass the data from PHP code ?
Just think, if you can be able to pass data from PHP to your JavaScript, then you can also be able to control your JavaScript behavior based on how you have configured your module. Drupal.settings fulfill your wish in a simple way.
So what are we waiting for, lets take a look to an example:

drupal_add_js(array('your_module_name' => array(

    'your_info_variable' => 'your_passed_info'

)), 'setting');

Illustration :
Now question is why we have used the drupal_add_js() function. In drupal_add_js() function we can use ‘setting’ parameter which will be accessible by Drupal.settings in JavaScript code and this is the thing which will help us to send our infos. So let’s take a look to the function structure:

drupal_add_js($data = NULL, $options = NULL)

For this we have to mention the proper parameter name ( which is ‘setting’ ) as the option at the last.

Now coming to the data part which we want to pass to our JavaScript. For this, first we have to mention our module name which will contain the data in an array format. This array can also be provided separately as below:

$your_passed_info = array(

    'your_info_variable_1' => 'your_passed_info',
    'your_info_variable_2' => 'your_passed_info'
    ...
    ...

);

Now, we can use this info array as below:

drupal_add_js(array(
    'your_module_name' => $your_passed_info
), 'setting');

Now it’s time to access your settings in JavaScript code

var yourInfoVariable = Drupal.settings.your_module_name.your_info_variable;
var yourInfoVariable1 = Drupal.settings.your_module_name.your_info_variable_1;
var yourInfoVariable2 = Drupal.settings.your_module_name.your_info_variable_1;

Here you can see, we are using Drupal.settings for getting the passed data with the variable names which we have used in our PHP code.

So now, you can enjoy with your passed infos using those JavaScript variables.

HAPPY DRUPALIZING 🙂

Advertisements