Pass request headers in a jQuery AJAX GET call

490,475

Solution 1

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

Solution 2

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.

Solution 3

$.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) {
                
            }
        });
Share:
490,475

Related videos on Youtube

Cranialsurge
Author by

Cranialsurge

Updated on July 05, 2020

Comments

  • Cranialsurge
    Cranialsurge almost 4 years

    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); }
          });
    
  • matthew_360
    matthew_360 over 11 years
    i know this is super-old by now. but I wanted to add that there should be a comma after: beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');}
  • Lukas
    Lukas over 11 years
    Yes: $.ajaxSetup({headers: {"X-Test-Header": "test-value"}})
  • Glen Selle
    Glen Selle about 10 years
    The jQuery docs don't recommend using $.ajaxSetup() anymore (api.jquery.com/jQuery.ajaxSetup)
  • MiniRagnarok
    MiniRagnarok over 9 years
    @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.
  • user1940268
    user1940268 over 9 years
    beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');} works well in chrome and firefox but not in IE8. there is no X-Test-Header send. how to fix it? Thx
  • Ghanshyam Baravaliya
    Ghanshyam Baravaliya about 8 years
    i have tried but it throw error when i am passing header detail in using "jquery-1.11.1.min.js"
  • Erik Philips
    Erik Philips about 8 years
    @Trip My recommendation for globally... write your own wrapper for ajax calls (abstraction) instead of calling $.ajax().
  • thedanotto
    thedanotto almost 8 years
    see below answer, much more relevant
  • Si8
    Si8 over 7 years
    What if I want to add X-Test-Header and X-Test-Header to the beforeSend?
  • Jeb50
    Jeb50 about 7 years
    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.
  • enthusiast
    enthusiast about 7 years
    you may want to try something like - string[] ids = System.Web.HttpContext.Current.Request.Headers["logonID"].Sp‌​lit(',');
  • Kirby
    Kirby over 6 years
    is this possible with "jsonp"?
  • Emmanuel Gleizer
    Emmanuel Gleizer over 6 years
    be aware this doesn't work with jsonp (see stackoverflow.com/questions/7433556/…) for jsonp refere to @Adam response
  • Emmanuel Gleizer
    Emmanuel Gleizer over 6 years
    this response is the correct one if you use jsonp, but if you don't see @Lukas response below. Warning if you both use https for url AND jsonp it won't work.
  • Serhii Popov
    Serhii Popov over 5 years
    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.
  • Rishav
    Rishav over 5 years
    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
    Rishav over 5 years
    What If i want to pass a json object in 'x-text-header'? I tried it and it receives [Object Object]
  • Lukas
    Lukas over 5 years
    @Rishav JSON objects are not allowed in headers. You'll have to JSON.stringify it and then parse it on the server.
  • tree
    tree over 3 years
    dataType should be written ad datatype
  • Gabor Garami
    Gabor Garami almost 3 years
    If you really want to use JSON in a header, I recommend you to JSON.stringify and Base64 encode it. Special characters could cause issues in proxies between the browser and the backend.