I am looking for a Drupal way of detecting AJAX request. I need to check this inside hook_form_alter() when embedding views with AJAX support.

How can I understand a request is an AJAX request?


For Drupal 7 there's nothing special in the API, just use plain PHP:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  // AJAX request

For Drupal 8, the Symfony request object has a helper method:

// Example for brevity only, inject the request_stack service and call 
// getCurrentRequest() on it to get the request object if possible.
$request = \Drupal::request();
$is_ajax = $request->isXmlHttpRequest();

You may consider using 'current_path()` and verify the path contains ajax in it.

$current_path = current_path();
if (strpos($current_path, 'ajax') !== FALSE) {
  // This is an AJAX request.
  • 6
    Might work 95% but it seems like this isn't guaranteed. Firstly isn't it only convention that string 'ajax' is part of the path for ajax requests? Any contrib module could register any path it chooses. Secondly couldn't a non-ajax path happen to contain the string 'ajax'? E.g. could set path for a view or panels page to 'myajaxpage'?
    – AdamS
    Oct 31 '15 at 5:44

AJAX request in scope of working with forms in Drupal would mean that form must be rebuild. To detect that form must be rebuild one should check for:

$form_state['rebuild'] == TRUE;

Since there is no bullet-proof method of checking AJAX request (as HTTP_X_REQUESTED_WITH can be spoofed), here is another alternative based on the URL:

if (end((arg())) == 'ajax') {
  // AJAX request

Works for views (in case when last URI item contains 'ajax' word).

See also: How to check if the request is an AJAX request with PHP?

  • I think in the case of file/ajax and media/ajax there are likely to be extra parameters on the URL, so ajax won't be at the end. E.g. /file/ajax/field_user_picture/und/0/form-XXXXXXXXXXXXXXXXXXXXXXXXXX
    – AdamS
    Oct 31 '15 at 5:37

How I did it was using:

$request = $_SERVER['REQUEST_URI']

There I detected the ?_wrapper_format=drupal_ajax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.