Skip to content

Instantly share code, notes, and snippets.

Last active April 5, 2022 01:03
What would you like to do?
Drupal 8 - detect if we're in an ajax request, and if building the form for the first time, or re-building within the input processing.
use Drupal\Core\Form\FormStateInterface;
function example_ajax_form_alter() {
$ajax_form_request = \Drupal::request()->query->has(FormBuilderInterface::AJAX_FORM_REQUEST);
if ($ajax_form_request) {
if (!$form_state->isProcessingInput()) {
\Drupal::logger('example')->notice('first pass');
else {
\Drupal::logger('example')->notice('second pass');
Copy link

This didn't work for me. I used (which isn't drupal specific):
$is_ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

Copy link

What about this?

$is_ajax = \Drupal::request()->isXmlHttpRequest();

Copy link

proteo commented Apr 5, 2022

That worked great @lonalore, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment