psvs
psvs

Reputation: 199

If an AJAX REST API succeeds or fails, how do I access the request headers within the success or error callbacks?

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

Answers (3)

Sarvesh Mahajan
Sarvesh Mahajan

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

nishil bhave
nishil bhave

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

Pointy
Pointy

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.

More information at MDN.

Upvotes: 1

Related Questions