2

What is the best way within my PHP script to differentiate between a normal browser GUI request and an AJAX request?

Mark
  • 2,669
  • 2
  • 17
  • 13

2 Answers2

5

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for the info. So would using JavaScript to send the 'X-Requested-With' header be reliable across all browsers? Or would using an additional GET param such as: my_page.php?request_method=ajax be more reliable? – Mark Mar 31 '12 at 08:53
  • Adding new headers with `setRequestHeader` is well supported. – Quentin Mar 31 '12 at 09:00
0

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.

cantlin
  • 3,236
  • 3
  • 21
  • 22
  • That seems like quite a good solution. So is xhr.setRequestHeader('X-YourApp-AJAX', '1'); going to work across all browsers? – Mark Mar 31 '12 at 08:55
  • The underlying ``XMLHttpRequest`` object is implemented across all modern browsers. IE6 doesn't support it [by that name](http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx), but your Javascript framework of choice will save you from needing to manually define it where not present. – cantlin Mar 31 '12 at 09:04