Did you find this useful?
Socialize it today.


Retrieve Header Information with Ajax

Wednesday, August 01, 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!


Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Bulletproof Ajax The Complete Reference Ajax HTML CSS and JavaScript Editor