Detecting AJAX request in a PHP page?

Is this the surest way of detecting an AJAX request, or is it safer to add a custom header to my jQuery.ajax code?

function isAjaxRequest() {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        return TRUE;
    }
}
return FALSE;

}

I do care about older browsers and older PHP installations as I want to make my code work in as many situations as possible.

Answers


Is this the surest way of detecting an AJAX request

It's about as sure as you are likely to get.

or is it safer to add a custom header to my jQuery.ajax code?

Why duplicate effort? jQuery is already adding that custom header.


It would be cleaner to forget about having the server care about the difference between "Ajax" and "Not Ajax" and instead of care about (for instance) "Want JSON" and "Want HTML".

You can use the HTTP Accept header for that.


There is no safe way to detect Ajax requests.

Ajax request have the same pattern as GET/POST normal pageviews.

HTTP Headers starting with X_ are custom fields which are not even implemented in every Ajax library.

You should not rely on this information and therefore implement a completely different way of what you want to achieve.

I do care about older browsers and older PHP installations as I want to make my code work in as many situations as possible.

If this is your goal, forget about the header.

The best and shortest answer is right next to mine from Quentin:

It would be cleaner to forget about having the server care about the difference between "Ajax" and "Not Ajax" and instead of care about (for instance) "Want JSON" and "Want HTML".

On the internet, you can't ask "Where are you from and which ride did you take" and get a reliable answer at all. The interwebs are not designed to fit this kind of question.


public function getIsAjaxRequest()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
    }

Need Your Help

Centering images inside Bootstrap gridsystem

html css image twitter-bootstrap twitter-bootstrap-3

I want to center my images inside the Bootstrap grid like this - http://i.imgur.com/weTvp5Q.jpg; the image should be centered in the blue box (both on desktop and mobile).

Proving lemma with implication based on functions

proof coq

I want to prove the lemma below. I am trying to to use tactic 'destruct', but I