Hey all,
I'm making a javascript apt, that would use the drupal user name as part of its functioning. Anyone know how I could get the name? I thought about making an AJAX like callback, but that always gives me a webpage (thats the short of it). I can hack this method working, I'm sure.

But, is there a real way of getting the user name? Is it possible to get it from the cookie?

Comments

rszrama’s picture

Two things... you can just use a callback if you want. Have the function the menu item points to be something simple like so:

  function get_username() {
    global $user;
    print $user->name;
    exit();
  }

Simple but effective... and you can really just extend this function to be a generic variable grabber... pass in an array of variables you want to get, parse the array, and print the results. It's quite simple to past in a $_POST array using jQuery's $.post() method. Check it out at http://www.visualjquery.com or in examples around Ubercart.org.

Or... the easier way... ; )

Just expose this as a JS variable on page load using drupal_add_js(). Just make sure some hook or function in the module that is getting called on the pageloads you need the username has code like:

  global $user;
  drupal_add_js('var drupal_username = '. $user->name, 'inline');

Now access it in the JS like a normal JS variable.

----------------------
Current Drupal project: http://www.ubercart.org

danbh’s picture

Thats just the information i needed. Thanks so much!

dstorozhuk’s picture

Actually you need to use drupal js settings.
So the correct way in php side is:

global $user;
$setting = array('module_name' => array('user_name' => $user->name));
drupal_add_js($setting, 'setting');

After that, in js side, if you are in behavior.attach:

Drupal.behaviors.module_name = {
  attach: function (context, settings) {
  var user_name = settings.module_name.user_name;
  }
}

Or access directly from Drupal scope from any part of your code:

var user_name = Drupal. settings.module_name.user_name;

Drupal development, migration and support: https://itech4web.com

jaypan’s picture

For D7, the following:

global $user;
$setting = array('module_name' => array('user_name' => $user->name));
drupal_add_js($setting, 'setting');

Can also be attached as part of a render array in the following manner:

global $user;

$page['#attached']['js'][] = array
(
  'type' => 'setting',
  'data' => array
  (
    'moduleName' => array
    (
      'userName' => $user->name,
    ),
  ),
);

Where $page is the render array that is being returned. This render array can be a form, or any other render array in the site. Note that if it is a block, you can create #attached as part of the 'content' attribute of the block (see this tutorial for more details).

Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.