Drupal 7 check if user is logged in from javascript

Drupal 7 check if user is logged in from javascript

Drupal 7 comes with jquery cookie plugin which can be find under

misc/jquery.cookie.js

This plugin can be used to check if user is logged in or not directly from Jquery. We do that by checking if the cookie DRUPAL_UID exists and its value is not equal to 0.

var cookie_value = jQuery.cookie("DRUPAL_UID");
if(cookie_value != 0)
{
    // Drupal user is authenticated...do some code...
}
else {
  // Drupal user anonymous user...do some code...
}

However Drupal will not load cookie plugin for anonymous users and you might encounter following error:

Error: TypeError: jQuery.cookie is not a function

Therefore we need to explicitly include cookie library before calling our javascript file:

<?php
drupal_add_library('system', 'jquery.cookie');
?>