Categories

jQuery AJAX Headers

Posted on: October 4, 2016 by Dimitar Ivanov

Every time when an AJAX request is initiated a bunch of headers as Accept, Host, User-Agent and few others are send to the server. The browser automatically set their values. In certain situations, you may want to change these values or send additional headers along the AJAX request. You can add standard headers as Authorization, Content-Type as well as non-standard headers as X-Requested-With, X-Csrf-Token or completely custom ones. This blog post describes how to set custom ajax headers by using the jQuery and XMLHttpRequest.

jQuery ajax headers

jQuery made the setting of custom ajax headers extremely easy using the headers property and beforeSend callback function both part of jQuery.ajax() interface.

  • headers - a plain javascript object consisted of key/value pairs to sent along with ajax request. Supported since jQuery v1.5
    $.ajax({
        headers: {
            'Authorization': 'Basic ' + btoa('myuser:mypswd'),
        	'Order-Num': 123
        },
        url: myUrl
    });
    
  • beforeSend(jqXHR, settings) - a callback function that can be used to modify the jqXHR object, e.g. to set custom headers.
    $.ajax({
        beforeSend: function (jqXHR, settings) {
            jqXHR.setRequestHeader('Authorization', 'Basic ' + btoa('myuser:mypswd'));
        },
        url: myUrl
    });
    

Overwrite AJAX headers

The headers property can be easily overwritten using the jQuery beforeSend function since it has bigger precedence.

$.ajax({
    beforeSend: function (jqXHR, settings) {
        jqXHR.setRequestHeader('Authorization', 'Basic ' + btoa('myuser:MyNewPswd'));
    },
    headers: {
        'Authorization': 'Basic ' + btoa('myuser:mypswd')
    },
    url: myUrl
});

XMLHttpRequest AJAX headers

For those who prefer to use XMLHttpRequest API instead of jQuery, adding a custom ajax headers is possible with the setRequestHeader method.

  • setRequestHeader(header, value) - adds custom headers to the HTTP request using the given header name and its value.
    var xhr = new XMLHttpRequest();
    xhr.open('GET', myUrl, true);
    xhr.setRequestHeader('Payment-Id', 'ABC0001');
    xhr.setRequestHeader('Order-Num', 123);
    xhr.setRequestHeader('Order-Num', 456);
    xhr.send(null);
    

    Multiple headers with the same name are combined and send as one as shown on Figure 1.

    AJAX setRequestHeader
    Figure 1. Custom AJAX headers in effect
Conclusion

Adding of custom ajax headers to cross-origin request can be tricky because it will trigger a preflight request.

Make your website more secure by using the HTTP Headers for Wordpress, and never face a cross-origin issue again. Oh yes, it's FREE.
See also
References
Share this post

If you have questions about jquery AJAX headers please leave a comment below. And don't forget to share this blog post if you like it. Thanks so much for reading!


0 Comments

Leave a comment

Captcha