I was trying to add custom headers before sending ajax request to the server (controller in .NET MVC), but I am not able to send it, here is what I am using as of now
$.ajax({
type: 'POST',
url: url,
headers: {
"CustomTestHeader1":"Custom Test header value 1",
"CustomTestHeader2":"Custom Test header value 2"
},
success: function (data) {
}
});
The above Ajax jQuery Code not working for me.
So, how to add custom headers in the Ajax request?
Above code should work, and if it is not working, try adding headers using jQurey ajax as shown below
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("custom_header", "value");
},
success: function(data) {
}
});
If you want to send the custom header for every future request, then you could use the following
$.ajaxSetup({
headers: { "CustomHeader": "myValue" }
});
This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request.
OR set multiple headers for every request
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
Hope it helps.
You can also use XMLhttprequest, instead of jQuery to set headers
function setHeaders(headers){
for(let key in headers){
xhr.setRequestHeader(key, headers[key])
}
}
var req = new XMLHttpRequest();
req.onreadystatechange=handleStateChange;
req.open("GET", "url", true);
setHeaders({"Host":"api.domain.com","X-Requested-With":"XMLHttpRequest","contentType":"application/json"}); //set multiple headers
req.send();
This is JS based solution.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly