Skip to content Skip to sidebar Skip to footer

Xmlhttprequest Not Adding Header - "x-requested-with: Xmlhttprequest"

I have an ajax call where I used jQuery.ajax() to make a request to an mvc action. This all worked fine. However due to some forms having a file control I changed it from using jQu

Solution 1:

X-Requested-With is automatically added by jQuery. You can just as easily add it yourself with AjaxRequestObject.setRequestHeader(). Docs


Solution 2:

I was having troubles with detecting if my request was ajax. So, maybe this sample will save someone a minute or two:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', URL, true);  // `true` for async call, `false` for sync.

// The header must be after `.open()`, but before `.send()`
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

xmlhttp.onreadystatechange = function() {
    // 4th state is the last:
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { ... }
};
xmlhttp.send();

Tested with Flask.


Solution 3:

You can override natively all XMLHttpRequest.open method calls and add in it X-Requested-With header like:

(function () {  

    // @author https://github.com/stopsopa jfdsa78y453cq5hjfd7s877834h4h3

    if (window.XMLHttpRequest.prototype.onOpen)  {
        return console.log('XMLHttpRequest.onOpen is already defined');
    }

    function over(method, on, off) {

        var old = window.XMLHttpRequest.prototype[method];

        if (!old.old) {

            var stack = [];

            window.XMLHttpRequest.prototype[on] = function (fn) {
                if (typeof fn === 'function') {
                    stack.push(fn);
                }
            }

            window.XMLHttpRequest.prototype[off] = function (fn) {
                for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
                    if (stack[i] === fn) {
                        stack.splice(i, 1);
                        break;
                    }
                }
            }

            window.XMLHttpRequest.prototype[method] = function () {
                var args = Array.prototype.slice.call(arguments);

                var ret = old.apply(this, args);

                for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
                    stack[i].apply(this, args);
                }

                return ret;
            }

            window.XMLHttpRequest.prototype[method].old = old;
        }
    }

    over('open', 'onOpen', 'offOpen')

    XMLHttpRequest.prototype.onOpen(function () {
        this.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    });
}());

Post a Comment for "Xmlhttprequest Not Adding Header - "x-requested-with: Xmlhttprequest""