[Drupal] How to retrieve content stored in session variable using JQuery?

| | 1 min read

Many a times Drupal users face the problem of not being able to access the php variables in jquery function . One way of accessing this variables is using ajax but this causes time delay in sending requests.This time delay can be minimized using drupal.settings.If you are not sure how to tackle this problem then read on.

Php variables can be stored using drupal_add_js function and can be accessed using drupal.settings,drupal_add_js function adds a setting to Drupal's global storage of JavaScript settings and these variables can be accessed using drupal.settings.

For example if you want to store a php variable then add the following code in php.

 $variable = value;
 drupal_add_js(array('myModule' => array('key' => $variable)), 'setting');

In Jquery function the variable can be accessed using drupal.settings

var value = Drupal.settings.myModule.key;

Tips: If you are facing problem in storing the variable, then the above php code can be included in module_init() function.