brrocks28
7/18/2016 - 8:04 AM

Drupal ADD_JS WITH DATA #ATTACH JS

Drupal ADD_JS WITH DATA #ATTACH JS

// normal add_ja

In your MODULENAME.module file use the following code.

$testVariable = 'himanshu';
drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');


And in MODULENAME.js use the following one.

(function($) {
  Drupal.behaviors.MODULENAME = {
    attach: function (context, settings) {
      alert(settings.MODULENAME.testvar);
    }
  };

})(jQuery);
//In your MODULENAME.module file use the following code. use as per needed

$form['notification_email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email')
);
$form['notification_email']['#attached']['js'][] = array(
  'data' => array('setting_name' => $js_settings),
  'type' => 'setting'
);
$form['notification_email']['#attached']['js'][] = array(
  'data' => 'file.js',
  'type' => 'file'
);
$form['notification_email']['#attached']['js'][] = array(
  'data' => 'http://domain.com/file.js',
  'type' => 'external'
);

///////////////////////////////////////////////

// Method 1, JS or CSS
$element['#attached']['js'][] = $data; // This is assumed to be a local file name. JS or CSS


// Method 2, JS or CSS
$element['#attached']['js'][$data] = $options; // $data can be an external URI, a local file, or inline code.


// Method 3, JS or CSS.  JS settings *must* use this version.
$options['data'] = $data; // $data can be any type
$element['#attached']['js'][] = $options; // Brackets must be empty, or contain a numeric index


// Method 4, libraries are special
$element['#attached']['library'][] = array(
  $module,
  $name,
);




//In your MODULENAME.module file use the following code. use as per needed
//////////////////////////////////////////////////////////////////////////////////////////////

      $form['#attached']['js'][] = array(
        'data' => array('pincode' => $pincode),
        'type' => 'setting',
      );

//In your js file use the following code. use as per needed
//////////////////////////////////////////////////////////////////////////////////////////////

       var pincode = Drupal.settings.pincode;
       console.log('bhavesh');
       console.log(pincode);