Get Joomla user_id using a Jquery Ajax

2019-08-20 01:57发布

I have the following PHP script file.php in my Joomla site:

$user = JFactory::getUser();
$usr_id = $user->get('id');

If I run it directly, using in HTML:

include_once "file.php";

It will get the user id, no problem.

However, if run it through an Ajax request:

$.ajax({
    url: "other.php",
...

Where other.php is:

include_once "file.php";

I get the error:

Fatal error:  Class 'JFactory' not found in file.php on line 3

Why? Any help!?

1条回答
在下西门庆
2楼-- · 2019-08-20 02:39

You need to import the Joomla library in order to use the JFactory class. To import the library, add the following to the top of your file:

define( '_JEXEC', 1 );
define( 'JPATH_BASE', dirname(__FILE__) ).'/../..' );

require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );

$mainframe = JFactory::getApplication('site');
$mainframe->initialise();
查看更多
登录 后发表回答