Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a user is logged_in in a Drupal site via JavaScript?

I know how to check if the user is logged in through PHP, but I need to do some styling when an event occurs, and I created a separate JavaScript file for this. Is this a Drupal variable or something which I can reference too?

like image 417
samwell Avatar asked Apr 16 '12 22:04

samwell


1 Answers

Create a new custom module with hook_init implementation.

function [YOUR_MODULE]_init()
{
    global $user;
    drupal_add_js(array('user_js_uid' => $user->uid), 'setting');
}

Then in your javascript code, check for the value of the variable defined in the module user_js_uid.

if(Drupal.settings.user_js_uid == 0)
{
    // execute code for non logged in users
}
else
{
    // execute code for logged in users
}
like image 148
Muhammad Reda Avatar answered Sep 26 '22 11:09

Muhammad Reda