Reputation: 199
For example, I have:
$.ajax({
type: 'POST',
url: 'https://jsonplaceholder.typicode.com/todos',
data: { name: 'random name' },
headers: { 'x-my-custom-header': 'XYZ' },
success: function(successResp) {
console.log(successResp);
},
error: function(errorResp){
console.log(errorResp);
}
});
How can I access 'x-my-custom-header' from the request header within success or error callbacks?
Upvotes: 1
Views: 45
Reputation: 924
You can try this, as request
object is accessible if requesting from success callback as third parameter:
$.ajax({
type: 'POST',
url:'https://jsonplaceholder.typicode.com/todos',
data: { name: 'random name' },
headers: { 'x-my-custom-header': 'XYZ' },
success: function(data, textStatus, request){
alert(request.getResponseHeader('some_header'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('some_header'));
}
});
And for more details, please visit : https://api.jquery.com/jQuery.ajax/
Upvotes: -1
Reputation: 632
Store your header in a variable.
let customHeader = { 'x-my-custom-header': 'XYZ' };
$.ajax({
type: 'POST',
url: 'https://jsonplaceholder.typicode.com/todos',
data: { name: 'random name' },
headers: customHeader,
success: function(successResp) {
console.log(customHeader);
},
error: function(errorResp){
console.log(customHeader);
}});
Upvotes: 1
Reputation: 413702
If you don't explicitly include a context
property in the $.ajax()
settings, then in your "success" etc. handlers this
will refer to the settings object itself. Thus, this.headers
will give you the additional header properties.
Upvotes: 1