258

I am trying to pass request headers in an AJAX GET using jQuery. In the following block, "data" automatically passes the values in the querystring. Is there a way to pass that data in the request header instead ?

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         success: function() { alert('Success!' + authHeader); }
      });

The following didn't work either

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         beforeSend: { signature: authHeader },
         async: false,                    
         type: "GET",
                    success: function() { alert('Success!' + authHeader); }
      });
AstroCB
  • 11,800
  • 20
  • 54
  • 68
Cranialsurge
  • 5,692
  • 7
  • 38
  • 39

3 Answers3

415

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

From http://api.jquery.com/jQuery.ajax:

headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

Lukas
  • 9,315
  • 2
  • 34
  • 45
  • 81
    Yes: `$.ajaxSetup({headers: {"X-Test-Header": "test-value"}})` – Lukas Jan 26 '13 at 05:59
  • 6
    The jQuery docs don't recommend using $.ajaxSetup() anymore (http://api.jquery.com/jQuery.ajaxSetup/) – Glen Selle Jun 09 '14 at 22:06
  • 2
    @Glen Their reasoning is that plugins might be expecting default settings to work. Personally, I think it's a given that if you globally change something, something that was depending on the default settings might not work. – MiniRagnarok Oct 13 '14 at 17:36
  • 1
    @Trip My recommendation for globally... write your own wrapper for ajax calls (abstraction) instead of calling $.ajax(). – Erik Philips Jun 09 '16 at 16:23
  • be aware this doesn't work with jsonp (see https://stackoverflow.com/questions/7433556/jquery-jsonp-ajax-authentication-header-not-being-set) for jsonp refere to @Adam response – Emmanuel Gleizer Mar 14 '18 at 07:27
  • Be aware, if you send cross-domain request you must allow your custom header in .httaccess with `Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, ..., x-test-header"`, otherwise an error `Access to XMLHttpRequest at 'http://...' from origin 'http://...' has been blocked by CORS policy: Request header field X-Test-Header is not allowed by Access-Control-Allow-Headers in preflight response.` – Serhii Popov Dec 06 '18 at 10:43
  • What If i want to pass a json object in 'x-text-header'? I tried it and it receives `[Object Object]` when I do so – Rishav Mar 27 '19 at 08:33
  • 1
    @Rishav JSON objects are not allowed in headers. You'll have to JSON.stringify it and then parse it on the server. – Lukas Mar 27 '19 at 16:51
309

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Adam
  • 39,529
  • 15
  • 101
  • 139
50

$.ajax({
            url: URL,
            type: 'GET',
            dataType: 'json',
            headers: {
                'header1': 'value1',
                'header2': 'value2'
            },
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
               // CallBack(result);
            },
            error: function (error) {
                
            }
        });
enthusiast
  • 817
  • 7
  • 10
  • Using jQuery 1.7.2, C# API 2.x, when trying to extract from header `HttpRequestMessage r = new HttpRequestMessage(); int mylogonID = Convert.ToInt32(r.Headers.GetValues("logonID"));` error out because **The given header was not found.** because r.Headers is empty. – Jeb50 Apr 15 '17 at 16:48
  • you may want to try something like - string[] ids = System.Web.HttpContext.Current.Request.Headers["logonID"].Split(','); – enthusiast Apr 17 '17 at 07:10
  • dataType should be written ad datatype – tree Oct 09 '20 at 15:07