Retrieve Header Information with Ajax

Wednesday, August 1, 2012

The XMLHttpRequest object includes two methods that allow you to retrieve either all of the response header information, or certain fields within the response header. The two methods are getAllResponseHeaders and getResponseHeader. In this tutorial, we will take a closer look at both methods.


Example

We will use the following HTML for the examples listed below.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  callFunction(){
  // ... JavaScript code
  }
</script>
</head>
<body>
 <img id="img1" onclick="callFunction()" src="go.png" /> ; 
 <div id="div1"> <!-- Some Content --> </div>
</body>
</html>


Syntax

xhr.getAllResponseHeaders();
xhr.getResponseHeader(header);

If you are interested in retrieving all response headers, use the getAllResponseHeaders() method. If you only need access to a particular header, use the getResponseHeader(header) method and replace the 'header' variable with the name of the header you are interested in retrieving. Here are some examples:


XMLHTTPRequest Response Header Methods

MethodDescription
getAllResponseHeaders()Returns header information
getResponseHeader(header)Returns specific header information


getAllResponseHeaders()

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("div1").innerHTML = xhr.getAllResponseHeaders();
        }
    }


click here
Click the icon to retrieve all Response Headers!


getResponseHeader(header)

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("div1").innerHTML = xhr.getResponseHeader('Response');
        }
    }


click here
Click the icon to retrieve only the 'Content-Type' header!


Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

Ajax for Dummies HTML CSS and JavaScript Editor The Complete Reference Ajax