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) {
}
});
Related videos on Youtube
Author by
Cranialsurge
Updated on July 05, 2020Comments
-
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 over 11 yearsi 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 over 11 yearsYes:
$.ajaxSetup({headers: {"X-Test-Header": "test-value"}})
-
Glen Selle about 10 yearsThe jQuery docs don't recommend using $.ajaxSetup() anymore (api.jquery.com/jQuery.ajaxSetup)
-
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 over 9 yearsbeforeSend: 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 about 8 yearsi have tried but it throw error when i am passing header detail in using "jquery-1.11.1.min.js"
-
Erik Philips about 8 years@Trip My recommendation for globally... write your own wrapper for ajax calls (abstraction) instead of calling $.ajax().
-
thedanotto almost 8 yearssee below answer, much more relevant
-
Si8 over 7 yearsWhat if I want to add
X-Test-Header
andX-Test-Header
to thebeforeSend
? -
Jeb50 about 7 yearsUsing 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 about 7 yearsyou may want to try something like - string[] ids = System.Web.HttpContext.Current.Request.Headers["logonID"].Split(',');
-
Kirby over 6 yearsis this possible with "jsonp"?
-
Emmanuel Gleizer over 6 yearsbe aware this doesn't work with jsonp (see stackoverflow.com/questions/7433556/…) for jsonp refere to @Adam response
-
Emmanuel Gleizer over 6 yearsthis 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 over 5 yearsBe 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 errorAccess 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 over 5 yearsWhat 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 over 5 yearsWhat If i want to pass a json object in 'x-text-header'? I tried it and it receives
[Object Object]
-
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 over 3 yearsdataType should be written ad datatype
-
Gabor Garami almost 3 yearsIf 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.