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

    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
: 4161 At:- 9/20/2018 5:41:24 AM
jQuery javascript add header in ajax request jquery ajax custom headers

1 Answers
profileImage Answered by:- Sam

Above code should work, and if it is not working, try adding headers using jQurey ajax as shown below

  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

    headers: { "CustomHeader": "myValue" }

This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request.

At:- 9/21/2018 1:15:06 PM

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

Full Name *

Email *

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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly