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']) &amp;&amp; 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-&gt;isXmlHttpRequest();