1

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.

2

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but the php page should return HTML regardless of what isAjaxRequest() says.
Might I ask why you want to test weather the request is via ajax then?
Yes, it will determine whether the PHP page will return a full page or just a block of HTML.
2

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.

Comments

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

1 Comment

Please put some explanation uppon your answer. What if my header is XmlHttpRequest ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.