I have a link generated within a JavaScript file that contains the following code:

jQuery(".url").append('<a href='+ path +'/extra/home><img src='+ pathimage +'></a>');

I would like to alter the path variables when user is not logged. In Drupal terms this would look like: global $user; if (user->uid == 0) {..redirect page.} or global $user; return !(bool) $user->uid;

How can I use the $user->uid property with JavaScript code?


You're looking for drupal_add_js(). You can use it to pass data from PHP to JavaScript. Something like the following should suffice:

 * Implementation of hook_init().
function modulename_init() {
  if (!user_is_logged_in()) {
      'modulename' => array(
        'path' => $logged_out_path
    ), 'setting');

Note that I am calling this from within an implementation of hook_init(), but really you can do this anywhere, be it from a module or a theme. Also note that I have provided a sufficient namespace for the value to live (i.e. within 'modulename' => 'path'). This will make it clear from JavaScript's point of view exactly who owns the variable (i.e. which module it came from), but more importantly will help to prevent collisions with settings in other modules.

From JavaScript you can access the value of $logged_out_path like this:

var path = Drupal.settings.modulename.path;
| improve this answer | |
  • This is what Drupal core does with Drupal.settings.basePath, which contains its base path. The code suggested in this answer doesn't expose sensitive information to JavaScript code. The important is that the module code doesn't assume the user reaching $logged_out_path has a specific role, or permission. – kiamlaluno Feb 17 '12 at 18:32
  • Thanks I found a way via context: conditions > user role > anonymous then reactions > theme_html that help me provide a class for body tag when is anonymous – drupal_stuff_alter Feb 29 '12 at 9:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.