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.
}
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?
How I did it was using:
$request = $_SERVER['REQUEST_URI']
There I detected the ?_wrapper_format=drupal_ajax