You are here: Reference > JavaScript > client-side > xml handling > methods > setRequestHeader (XMLHttpRequest)

setRequestHeader method (XMLHttpRequest)

Browser support:
Adds an HTTP header with the specified name and value to the request.
Request headers contain information about the sender, body of the request and required response.
First initialize an XMLHttpRequest object with the open method, then specify the necessary request headers with the setRequestHeader method and finally send the request with the send method.


object.setRequestHeader (name, value);
You can find the related objects in the Supported by objects section below.


Required. String that specifies the name of the request header to send.
The following list contains some of the commonly used names. If you need a detailed list, please visit the HTTP request headers (Wikipedia) page.
The content types that are acceptable for the response. It is the responsibility of the server to consider this requirement.
The character sets that are acceptable for the response. It is the responsibility of the server to consider this requirement.
The content type of the request body (for POST requests).
The current date and time when the request was sent.
Required. String that specifies the value of the HTTP request header.

Return value:

This method has no return value.

Example HTML code 1:

This example illustrates the use of the setRequestHeader method:
    <script type="text/javascript" src="ajax.js"></script>
    <script type="text/javascript">
        var httpRequest = null;

        function SendRequest () {
            if (!httpRequest) {
                httpRequest = CreateHTTPRequestObject ();   // defined in ajax.js
            if (httpRequest) {          
                    // The requested file must be in the same domain that the page is served from.
                var url = "news.xml";
       ("GET", url, true);    // async
                httpRequest.setRequestHeader ("Accept", "text/xml");
                httpRequest.onreadystatechange = OnStateChange;
                httpRequest.send (null);

        function OnStateChange () {
            if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
                if (IsRequestSuccessful (httpRequest)) {    // defined in ajax.js
                    alert ("Request complete.");
                else {
                    alert ("Operation failed.");
    <button onclick="SendRequest ()">Send request</button>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content