jQuery.ajax()
normally sends an X-Requested-With
header with XMLHttpRequest
set as the content. On the server (in PHP), I usually detect this by testing:
$is_ajax = $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'
In AngularJS, commonly found in $routeProvider.when()
, you can obtain a template from the server with templateUrl: '/path/on/server'
.
My problem is that templateUrl
requests seem to not set X-Requested-With
headers, so there's no way to distinguish templateUrl
requests from any other type of request.
Is there any way to get $routeProvider
to send X-Requested-With
as XMLHttpRequest
?
Reference:
$routeProvider Docs - (search templateUrl
)
jQuery jqXHR - see jqXHR.setRequestHeader("X-Requested-With", "XMLHttpRequest")
Using Angular v1.1.5
via Google CDN
Update: I found the actual commit where Angular developers removed X-Requested-With
from $http.get
. Wonder why they would do that?
Update: https://github.com/angular/angular.js/issues/1004 - discussion where header was removed.
Tip of the hat to Zerot in FreeNode's #angularjs
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$routeProvider.when('/', {
templateUrl: '/path/on/server',
controller: 'Ctrl'
});
});
Edit: to be more specific, this is the line you need somewhere:
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With