Drupal check request is Ajax

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

Other posts