How to add headers before sending Ajax Request using jQuery?


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?


Asked by:- neena
1
: 7541 At:- 9/20/2018 5:41:24 AM
jQuery javascript add header in ajax request jquery ajax custom headers







2 Answers
profileImage Answered by:- Sam

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.

2
At:- 9/21/2018 1:15:06 PM Updated at:- 9/27/2022 7:39:08 AM


profileImage Answered by:- vikas_jk

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.

0
At:- 9/27/2022 8:18:43 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use