Drupal 7 Get field value by machine name and pass to javascript I have tried to do this a couple of different ways, but I will just include the latest.

My task is to build a module that will get the STRING value of a taxonomy term by the machine name of the field when the page is rendered, and pass that STRING value to a javascript function to output data in a block.

Most recently, I have tried adding the code to the template.php file in the preprocess_html, page, node and process_html:

*The field is called 'field_test'

global $nid;
$node = node_load('12');
$test = $node-&gt;field_test['und'][0]['value'];
drupal_add_js(array('mymodule' =&gt; array('test' =&gt; $test)), 'setting');


Error in processes was a call to undefined index.
Error in page.tpl was a call to non object.

I also tried field_get_items:

$items = field_get_items('node', $node, 'field_test');
$first_item = array_shift($items);
$test = $first_item['value'];


In the node.tpl file, I tried adding this code:

&lt;?php
  $test = $node-&gt;field_test['und'][0]['value'];
  drupal_add_js(array('mymodule' =&gt; array('test' =&gt; $test)), 'setting');
?&gt;


No errors, but Drupal.settings.test returns undefined in the browser console.

I'll admit I am still new to the Drupal API. In addition to the correct code, I may also lack an understanding of the order in which Drupal components are loaded, and specifically where the code should be placed.

I would really appreciate any help you can provide.
It should be Drupal.settings.mymodule.test not Drupal.settings.test. All of this code should live in a preprocess hook (either page or node, whichever is more appropriate for your use case). For the node, you can try $node = menu_get_object('node');.

Example:

if ($node = menu_get_object('node')) {
  $tid = $node-&gt;field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' =&gt; array('test' =&gt; $term-&gt;name)), 'setting');
}


In your console (like Google Chrome) you can type Drupal.settings to see the entire object, and you should see mymodule as a part of it. Within that you will find test with the term name as a value.