AJAX - setRequestHeader()

1. What is setRequestHeader()?

The setRequestHeader() method in AJAX is used to set HTTP request headers before sending the request to the server.

It allows you to:

  • Define the type of data you are sending (e.g., JSON, form data).

  • Pass authentication tokens or API keys.

  • Add custom headers required by the server.


2. Syntax

xhr.setRequestHeader(header, value);

Parameters

Parameter Description
header The name of the HTTP header (e.g., "Content-Type", "Authorization")
value The value of the header (e.g., "application/json", "Bearer token")

3. Important Rules

  • Must be called after open() but before send().

  • Only works for requests where async = true or false.

  • If called multiple times with the same header, the values are merged (unless replaced manually).


4. Commonly Used Headers

Header Name Purpose
Content-Type Tells the server what kind of data is being sent.
Accept Tells the server what type of response the client expects.
Authorization Sends login tokens or API keys for authentication.
X-Custom-Header A custom header defined by developers.

5. Example 1 — Sending Form Data

var xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);

// Set the header for form data
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onload = function() {
    console.log(xhr.responseText);
};

// Send form-encoded data
xhr.send("name=John&age=25");

6. Example 2 — Sending JSON Data

var xhr = new XMLHttpRequest();
xhr.open("POST", "api.php", true);

// Set the header for JSON data
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = function() {
    console.log(xhr.responseText);
};

// Send JSON string
var data = JSON.stringify({ name: "Alice", age: 30 });
xhr.send(data);

7. Example 3 — Adding Authentication

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);

// Send token for authentication
xhr.setRequestHeader("Authorization", "Bearer 123456789abcdef");

xhr.onload = function() {
    console.log(xhr.responseText);
};
xhr.send();

8. Example 4 — Setting Multiple Headers

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);

// Multiple headers
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("X-Custom-Header", "MyValue");

xhr.onload = function() {
    console.log(xhr.responseText);
};
xhr.send();

9. Key Points to Remember

  • Always call setRequestHeader() after open() but before send().

  • If you don’t set Content-Type properly, the server may not understand the data.

  • For POST requests:

    • Use "application/x-www-form-urlencoded" for form data.

    • Use "application/json" for JSON.

  • Use Authorization headers when working with secure APIs.