Drupal - How can I detect AJAX request inside Drupal?

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() 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;
}

Tags:

Ajax