Get Joomla user_id using a Jquery Ajax

2019-08-20 02:27发布

问题:

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:

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();