skip to Main Content

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?

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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);
    }});
    
    Login or Signup to reply.
  3. 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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search