Search code examples
ajaxxmlhttprequestmootools

Custom headers on any ajax request using MooTools


I wonder if there's chance to add custom headers to any of my mootools based web application ajax requests by setup code that will run right after mootools js?

something according to ajaxSetup of jQuery.

Note: i'm not interested in Class Extending.

Thanks.


Solution

  • you can either subclass Request and define your own options with their own headers or you can just change the prototype.

    (function(){
        // sets defaults for all request instances
        this['X-Requested-With'] = 'Power';
    }.call(Request.prototype.options.headers));
    
    new Request({
        url: '/echo/html/',
        data: {
            html: 'hi'
        },
        method: 'post'
    }).send();
    

    etc etc.

    so basically:

    var myOptions = {
        'X-Requested-With': 'foo'
    };
    
    Object.merge(Request.prototype.options.headers, myoptions);
    

    and the extended:

    Request.Fixed = new Class({
    
        Extends: Request,
    
        options: {
            headers:  {
                'X-Requested-With': 'foo'
            }
        }
    });
    
    new Request.Fixed({
        url: '/echo/html/',
        data: {
            html: 'hi'
        },
        method: 'post'
    }).send();
    

    I'd recommend the extend unless you're solving a very particular CORS issue - at least it tells whoever reads the code it's not using a standard Request instance, easier to understand and maintain.

    I understand you're not interested in subclassing - however, it is the right thing to do, I have had such single line hacks come back and bite me in the backside when domains have changed / configs /code reused and people forgotten the tweak. makes for one hell of a journey to find the reason why it's all broken. Downside of subclassing is other subclasses that extend Request directly like Request.HTML and Request.JSON, they won't inherit the change.