Hi,

I need the username and the uid in my javascript file. I read that is is possible to convert php vars into js vars with the function drupal_to_js ?

How can i use this function and how i have access to this var in the js file?

thanks! ayti

Comments

criznach’s picture

drupal_to_js might be overkill because it creates JSON for an asynchronous request.

I think instead you could use drupal_add_js in your page template and add something like...

drupal_add_js('inline', 'var uid = '.$user->uid.';');
etc...

http://api.drupal.org/api/function/drupal_add_js/5

ayti’s picture

ty for your answer, but i can't still use the var in my js file.
my callback function in my module looks like this:

    ...
    //$username = $user->name;
    drupal_set_html_head('<script ..." type="text/javascript"></script>');
    //drupal_to_js($username);
    drupal_add_js("sites/all/modules/xgmap/map_functions.js");
    ...

and i need the username and the uid in my js file.

where exactly i have to put drupal_add_js in the page template?

and how can i pass the variable without changing the page template?

criznach’s picture

Your JS file is a static file that's not generated by php. Why can it not be in the page template? If you put it in the page template, it's available at the global scope to your JS file. If you absolutely must not have it in the page template, then you could use the JQuery get method once the page loads to request a drupal callback that returns the user id. But that just seems silly.

ayti’s picture

Thanks for your help. I've found a HowTo under follwing link:

http://drupal.org/node/127067

mooffie’s picture

A shorter/cleaner solution:

In you PHP:

drupal_add_js(array('mymodule' => array(
  'username' => 'Mike',
  'uid' => 123,
  'likes' => array('ice cream', 'peanuts', 'coffee'),
)), 'setting');

In your JS:

alert(Drupal.settings.mymodule.username);

criznach’s picture

Wow that's slick. I didn't know about that method. Thanks mooffie!