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?

1 Answer 1

3

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
    }
}
7
  • 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. Commented Apr 6, 2016 at 20:44
  • I am also having same issue as @GeorgeSexton had. Commented Jul 25, 2017 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
    Commented Jul 25, 2017 at 9:47
  • Nice one @Lodder . I adapted it to apply it to plugin. Its the roughly the same code. You saved my day. Commented Apr 3, 2020 at 17:50
  • 1
    @thednp Yes this is still possible. Feel free to post a new question if you're running into issues and need help.
    – Lodder
    Commented Mar 5, 2021 at 6:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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