Question

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:

Was it helpful?

Solution

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';

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top