ajax add custom header

AJAX Add Custom Header

If you want to add custom headers to your AJAX request, you can use the setRequestHeader() method.

Method 1: Using setRequestHeader()


var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.setRequestHeader('X-Custom-Header', 'CustomValue');
xhr.send();

In the above code, we create a new instance of XMLHttpRequest and open a GET request to the URL 'http://example.com'. We then use the setRequestHeader() method to add a custom header with the name 'X-Custom-Header' and the value 'CustomValue'. Finally, we send the request using the send() method.

Method 2: Using headers option in jQuery AJAX


$.ajax({
    url: 'http://example.com',
    type: 'GET',
    headers: {
        'X-Custom-Header': 'CustomValue'
    },
    success: function(data) {
        console.log(data);
    }
});

In the above code, we use the jQuery AJAX function to make a GET request to the URL 'http://example.com'. We pass an object with the headers property set to an object with the custom header name and value. We also specify a success callback function to handle the response data.

Method 3: Using fetch API


fetch('http://example.com', {
    headers: {
        'X-Custom-Header': 'CustomValue'
    }
})
.then(response => response.text())
.then(data => console.log(data));

In the above code, we use the fetch API to make a GET request to the URL 'http://example.com'. We pass an object with the headers property set to an object with the custom header name and value. We then chain two then() methods to handle the response data.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe