2

I'm using com_ajax for requests, and I've run into a problem.

I'm trying to determine if the user making an AJAX request is logged in. When I call JFactory::getUser(), it's returning a guest user, ID=0. Similarly JApplication->isAdmin() returns false. I'm guessing that's because com_ajax resides in the site side, not the administrator side. Is that right?

Is there any way to use com_ajax and distinguish if someone is authenticated? Alternatively, is there an equivalent to com_ajax on the administrator side? Do I have to write my own Ajax on an administrative component?

2

Assuming you using the correct naming conventions for you Ajax task in the URL and PHP function, you should have something like this:

helper.php

public static function myFunctionAjax()
{

}

Javascript file

var request = {
    'option' : 'com_ajax',
    'module' : 'mymodule',
    'method' : 'myFunction',
    'format' : 'raw'
};

$.ajax({
    type: 'POST',
    data: request,
    success: function(response) {
        // etc
    }
});

myFunction needs to use the same name as the PHP function you wish to execute (myFunctionAjax()).

The only different being is that PHP function needs Ajax on the end.

Then inside your PHP function, you can check if the user is logged in, like so:

public static function myFunctionAjax()
{
    $user = JFactory::getUser();

    if (!$user->guest)
    {
        // perform some magic
    }
    else
    {
        // Sorry, you must be logged in
    }
}
  • 1
    I tried this and I got the error: LogicException: Module mod_com_connectdaily is not published, you do not have access to it, or it's not assigned to the current menu item. I ended up implementing a controller in the component to implement AJAX for this call. – George Sexton Apr 6 '16 at 20:44
  • I am also having same issue as @GeorgeSexton had. – vishnu Jul 25 '17 at 5:38
  • @vishnu - I have updated the Javascript with some changes that fix issues I've personally run into myself. Please check again. – Lodder Jul 25 '17 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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