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, XMLHttpRequest, and Fetch API.
jQuery made the setting of custom ajax headers
extremely easy using the headers
property and beforeSend
callback function both part of jQuery.ajax() interface.
$.ajax({ headers: { 'Authorization': 'Basic ' + btoa('myuser:mypswd'), 'Order-Num': 123 }, url: myUrl });
$.ajax({ beforeSend: function (jqXHR, settings) { jqXHR.setRequestHeader('Authorization', 'Basic ' + btoa('myuser:mypswd')); }, url: myUrl });
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 });
For those who prefer to use XMLHttpRequest API instead of jQuery, adding
a custom ajax headers is possible with the setRequestHeader
method.
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);
The Headers
interface of the Fetch API (successor of the XmlHttpRequest API) allows us to control the headers of an AJAX request.
var myHeaders = new Headers(); myHeaders.set("X-Men", "Wolverine"); myHeaders.set("X-Games", "Aspen"); myHeaders.append("X-Games", "Minneapolis"); fetch(myUrl, { headers: myHeaders }).then(function (response) {});
Multiple headers with the same name are combined and send as one as shown on Figure 1.
Adding of custom ajax headers to cross-origin request can be tricky because it will trigger a preflight request.
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!
Join our mailing list and stay tuned! Never miss out news about Zino UI, new releases, or even blog post.