Given is a Drupal 9 project.
How can I make use of Drupal functionality through an AJAX call?
web/modules/custom/mymodule/src/Appointment.php
namespace Drupal\mymodule;
class Appointment {
public function getUser() {
return \Drupal::currentUser()->id();
}
}
web/modules/custom/mymodule/src/ajax/getUser.php
<?php
namespace Drupal\mymodule;
require_once '../Appointment.php';
$appointment = new Appointment();
echo $appointment->getUser();
theme-source/my-theme/js/script.js
(function ($, Drupal) {
body.on('click', '#get-user', function(e) {
$.ajax({
url: '/modules/custom/mymodule/src/ajax/getUser.php',
type: 'post',
success: function (response) {
$('#get-user').after(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(textStatus + ' - Unable to get user');
console.error(errorThrown);
}
});
});
})(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.
web/modules/custom/secondmodule/secondmodule.module
function secondmodule_form_alter(&$form, &$form_state, $form_id) {
$appointment = new \Drupal\mymodule\Appointment();
dpm($appointment->getUser(), 'User');
}