Ajax libraries add a X-Requested-With: XmlHttpRequest
header in their requests, so you can test for its presence:
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XmlHttpRequest')) {
// not an ajax request
}
However a malicious user can easily send this header too, so don't use this to protect sensitive data.