Drupal.settings.mymodule is not an object I have implemented a hook_menu() with a callback to check user's privileges and a page callback to create the html. When I am in page_callback(), I retrieve a JSON string from a db and I'd like to pass this string to a JS script that will do some visualization.

function page_callback( $id ){
    $myjson = mymodule_query($id);
    $vars = array('key' =&gt; $myjson);
    drupal_add_js(array('mymodule', $vars), 'setting');
    drupal_add_js(drupal_get_path('module', 'mymodule').'/js/myjs.js');
    return '&lt;div id="graph-data"&gt;&lt;/div&gt;';
}


In the JS file, I have:

(function($){
    Drupal.behaviors.mymodule = {
        attach : function(context, settings) {
            if(Drupal.settings.mymodule.key !== ''){
                alert('Got it!');
            }
        } 
    };
}(jQuery));


When I try to execute this code, I get:

TypeError: undefined is not an object (evaluating 'Drupal.settings.mymodule.key')


Is there any other way in D7 to pass a php variable at runtime to a JS script?

EDIT: trying to follow the advice using render arrays, what is the best way to translate my code? Here's what I have:

function page_callback( $id ){
    $output_data = array(
      '#theme' =&gt; 'graph_data', // not sure here...
      '#vars' =&gt; array('key' =&gt; mymodule_query($id)),
      '#attached' =&gt; array(
         'js' =&gt; array(
              drupal_get_path('module', 'mymodule') .'/js/myjs.js',
         ),
         'css' =&gt; array(
              drupal_get_path('module', 'mymodule') . '/css/graph_data.css',
         ),
      )
    );
    return $output_data;
}
It should be:

drupal_add_js(array('mymodule' =&gt; $vars), 'setting');


But ideally you'd be using a render array instead, and loading the settings/files into the page with the #attached method.