17

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

28

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();
  • I'm trying to check if the request coming from image upload button. 'HTTP_X_REQUESTED_WITH' doesn't exist in $server array. Any Ideas? – Mouneer Nov 25 '15 at 13:42
  • saved hours !! much appreciated !! – JayKandari May 4 '16 at 14:45
  • Thanks, @Clive! – aserww106 Jul 18 '19 at 5:43
9

You may consider using current_path() in your hook, for checking if the path contains the word 'ajax' in it.

Ex:

$current_path = current_path();
if (strpos($current_path, 'ajax') !== false) {
    echo 'AJAX request detected!';
    exit;
}
  • 3
    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
0

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
0

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;
0

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.