Skip to content
the poor coder

ajax add custom header

Poor Man
Published
Reading time
1 min read
On this page

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()#

Text

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#

Text

$.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#

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC