user3236661
user3236661

Reputation: 792

HTTP_X_REQUESTED_WITH not working properly in firefox 4

I'm using this code to redirect my users, blocking ajax-only pages from their browser

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {}
else {
    header("Location: /");
}

It works fine on Google chrome, Firefox 26 and IE11, however in firefox 4, the header is triggered even when loading using ajax.

How can I fix this?

Upvotes: 3

Views: 4705

Answers (1)

dave
dave

Reputation: 64657

You could try to either set the HTTP_X_REQUESTED_WITH header yourself, or set a different header and check for it also:

$.ajaxSetup({
        beforeSend: function (request)
        {
            request.setRequestHeader("HTTP_X_REQUESTED_WITH",'xmlhttprequest');
            request.setRequestHeader("BACKUP_FIREFOX_AJAX", 'xmlhttprequest');
        }
 });

And then

if((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || 
   (isset($_SERVER['BACKUP_FIREFOX_AJAX']) && 
   strtolower($_SERVER['BACKUP_FIREFOX_AJAX']) == 'xmlhttprequest'))

Not sure if it will work given it's firefox 4 (really old version), but it's worth a shot.

Ok, on digging some more, there appears to be an old Firefox bug where 1) if an xhr gets redirected then the custom headers are lost, and 2) When "automatic proxy detection" is operating firefox will sometimes do an internal redirect which triggers the problem in 1.

So, you may need to do something other than a header... perhaps append a query string param to all outgoing ajax requests, I'm not sure if you'd need to modify the url directly or data for GET requests, so I'd just do both and hope it works:

$.ajaxSetup({
  beforeSend: function(jqXHR, settings) {
      if (settings.url.split('?').length > 1) {
         settings.url = settings.url + '&ajax=1';
      }
      else {
          settings.url = settings.url + '?ajax=1';
      }
   },
data: {
    ajax: '1'
  }
});

and then you could do:

if((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || 
$_GET['ajax']==1)

Upvotes: 6

Related Questions