Reputation: 2779
What is the best way within my PHP script to differentiate between a normal browser GUI request and an AJAX request?
Upvotes: 2
Views: 1105
Reputation: 754
This is an old question, but the existing answers are incorrect in 2024. It is now possible for server-side code to distinguishing incoming XHR/fetch requests from other requests by looking at the "Sec-Fetch-Dest" request header. In all modern browsers now the Sec-Fetch-Dest value for XHR/fetch requests is the literal string "empty". For other requests it's something else.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Dest
Upvotes: 0
Reputation: 3226
As far as the server is concerned, there is no particular difference between a normal request and one initiated by Javascript.
If you want to identify a particular brand of request, a reasonable approach is to pass a custom header.
$.ajax(uri, {
beforeSend: function(xhr) {
xhr.setRequestHeader('X-YourApp-AJAX', '1');
});
Providing you're using Apache, checking for the header you just set in your PHP is easy enough.
$headers = getallheaders();
if(isset($headers['X-YourApp-AJAX'])) {
// AJAX request
} else {
// ...
}
Edit
Looks like jQuery, amongst others, already passes an X-Requested-With
header in AJAX requests – use that in preference.
Upvotes: 0
Reputation: 943643
Not as such.
You can write your JavaScript in such as way to to leave some sort of identifier in the request headers that you could use though. See the XHR setRequestHeader
method.
A nice use of HTTP would be to modify the Accept
header and then do normal content negotiation. Then (for example), instead of caring if it is Ajax or not, you just care if an HTML response is preferred over a JSON response.
Another convention is to use the non-standard X-Requested-With
header with a value of XMLHttpRequest
. A number of JavaScript libraries will add this by default to any request using XHR.
Either of these techniques will only work with XMLHttpRequest or plugin based Ajax though. You can't set arbitrary HTTP headers for JSON-P or iframe based Ajax.
Upvotes: 4