Coderguy’s Blog

Thoughts on code

About

Hello, my name is Daniel Ice. I am a software developer in the Dallas, TX area. I enjoy learning about new technology. I mostly focus on PHP and Ruby on Rails.

The other day I found myself needing to know if a user was logged in to my Joomla site via javascript.  To accomplish this I did the following steps:

1. Add check function to user controller

Open up <your root joomla dir>/components/com_user/controller.php and add the following function:

public function check() {
  global $mainframe;

  $user =& JFactory::getUser();
  echo ($user->guest) "0" : "1";

  //don't send the full page, just the ajax response above
  $mainframe->close();
}

You could add this function to any controller you want, just made sense for me to add it to the user controller.  If you don’t want to modify a core component you could always add it to another custom component you have added.

2. Add javascript function

I am assuming your a using jQuery for your javascript library.  Just add the following function:

function loggedIn() {
if(1 == $.ajax({ type: "GET", url: "index.php?option=com_user&task=check", async: false }).responseText) {
  return true;
}
  return false;
}

Leave a Reply