Given is a Drupal 9 project.

How can I make use of Drupal functionality through an AJAX call?


namespace Drupal\mymodule;

class Appointment {
  public function getUser() {
    return \Drupal::currentUser()->id();



namespace Drupal\mymodule;

require_once '../Appointment.php';

$appointment = new Appointment();

echo $appointment->getUser();


(function ($, Drupal) {

  body.on('click', '#get-user', function(e) {
      url: '/modules/custom/mymodule/src/ajax/getUser.php',
      type: 'post',
      success: function (response) {
      error: function (jqXHR, textStatus, errorThrown) {
        console.error(textStatus + ' - Unable to get user');

})(jQuery, Drupal);

Error that is returned:

Fatal error: Uncaught Error: Class 'Drupal' not found in /var/www/html/web/modules/custom/mymodule/src/Appointment.php:318 Stack trace: #0 /var/www/html/web/modules/custom/mymodule/src/ajax/getUser.php(9): Drupal\mymodule\Appointment->getUser() #1 {main} thrown in /var/www/html/web/modules/custom/mymodule/src/Appointment.php on line 318

When testing, the getUser() function works and I can dpm the ID. When replacing the \Drupal::currentUser()->id(); call with a string, the AJAX call works properly. So I assume that through AJAX, Drupal is not accessible in this way.


function secondmodule_form_alter(&$form, &$form_state, $form_id) {
    $appointment = new \Drupal\mymodule\Appointment();
    dpm($appointment->getUser(), 'User');
  • Calls need to be to valid routes, not PHP files. Those routes need to return a Response object, XMLResponse, or JsonResponse. You're also doing a POST with no body. Please see the docs on this. You're trying to load a PHP file and nothing is bootstrapped.
    – Kevin
    Commented Aug 30, 2022 at 10:33
  • 1
    It is unnecessary to use require_once because autoloading is in effect.
    – mona lisa
    Commented Aug 30, 2022 at 11:49
  • @Kevin - Thanks for your help. The actual code actually does send data in a POST call, I forgot to change that in my example code above. Commented Aug 30, 2022 at 15:43

1 Answer 1


Thank for the directions Kevin. After creating a route and call its URL with jQuery allowed me to continue.


  path: /admin/config/mymodule/getuser
    _controller: '\Drupal\mymodule\Controller\GetUser::getUser'
    _access: 'TRUE'



namespace Drupal\databride\Controller;

use Drupal\databride\Appointment;
use Symfony\Component\HttpFoundation\Response;

class GetUser {
  public function getUser() {
    $appointment = new Appointment();
    $userdata = $appointment->getUser();

    return new Response($userdata);

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.