AJAX Response Headers

Chapter 7 7 mins

Learning outcomes:

  1. Some HTTP responses headers
  2. The getResponseHeader() method
  3. The getAllResponseHeaders() method

Introduction

Often times while working with AJAX, you may find it helpful to work with the headers of a response and perform different actions based on their values.

Fortunately with XMLHttpRequest() we get two dedicated methods to retrieve response headers i.e getResponseHeader() and getAllResponseHeaders(). We'll discover both of these methods in this chapter and consider some solid examples on the topic. Let's begin!

HTTP response headers

Before we can start to work with the headers of a response, we need to first take out some time to understand a few of them. Knowing even a bit about HTTP headers will definitely give you can upperhand over many AJAX developers; maybe even some pro out there!

Content-Type

Starting with the first in this list, we have the response header Content-Type.

Content-Type tells us about the MIME type of the requested file.

For example if you request for the file foods.txt, the response will come back with Content-Type set to text/plain. This means that the file is simply a plain text file.

Similarly for HTML files we get the header's value as text/html, for XML files as application/xml, for CSS files as text/css and so on.

You can check out the Content-Type for any file type you like, on your browser right now, by using either the Developer Tools and inspecting the file's metadata, or some pure AJAX. As you might've guessed we'll go with the latter approach. After all we're learning AJAX then why not implement it!

But before we see the AJAX implementation, let's consider some other response headers as well.

Content-Length

The Content-Length header tells us about the length of the content of a requested file i.e the size of the file, in bytes.

This is often times also referred to as the byte length of the file.

We can use this header to tell us how large or small a given file is and then likewise perform different actions on either case. Later in the next section we'll consider an example where we use Content-Length to check whether a given file is within 10MB of a size limit.

Last-Modified

The Last-Modified header gives us a date when, the server believes, the given file was last modified at.

If you're building a file handling application, this header can particularly come to your advantage. For example, if you want to open up a file using AJAX and then display its last modified date to the end user, you can simply call on the header Last-Modified present within the list of response headers for the file, and display it. This can directly do the job for you and thus save you from doing extra work!

Although a very rudimentary use case of Last-Modified, this example does give at least some practical-level application of the header. Once you start developing real and complex web applications, at some point in time, you might find it helpful to utilise this header in your project - who knows?

As a quick exercise on the topic, try thinking of some other practical applications of this header apart from the one we've discussed above. Let's see whether you can come with interesting ideas!

Getting a response header

Uptil now in this chapter we've seen a couple of HTTP response headers along with some brief summaries of what they tell us and how to practically get them into action. However what's still missing is an answer to the question: how can we get the values of these, or any other response headers in AJAX?

We need to have some way of pulling out the value from a given response header. Luckily we do have one - the getResponseHeader() method.

getResponseHeader() is used to get the value of a given header. The header's name goes into the method as an argument of type string, which then throws out its corresponding value.

If the header doesn't exist, getResponseHeader() returns an empty string.

For instance to get the value of Content-Type you'll write getResponseHeader("Content-Type"). Similarly for Last-Modified you'll go on like getResponseHeader("Last-Modified").

Header names are case-insensitive, which means that we can also write getResponseHeader("content-type") to get the value of Content-Type. It's just a convention to uppercase all first characters!

Consider the following example where we fetch a file foods.txt and alert its Content-Type, once it's received completely:

var xhr = new XMLHttpRequest();
xhr.open("GET", "foods.txt", true);

xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // alert the Content-Type of the requested file
        alert(this.getResponseHeader("Content-Type"));
    }
}

xhr.send();

This is the AJAX implementation of inspecting any file's MIME type, that we were discussing above. Just go on and change the name of the file (in the second argument of open()) and you'll get its MIME type alerted to you!

Live Example

Getting all response headers

Apart from getResponseHeader() which takes a header name and returns its value, the method getAllResponseHeaders() simply throws out a string containing all headers of a response.

Each name-value pair takes on a newline and is separated using a colon : and a space.

In the example below we use this method to output the whole header response for a given request inside a <pre> element. The reason we do so is to preserve newline characters in the returned string.

var pre = document.getElementsByTagName("pre")[0]; // pre element selected

var xhr = new XMLHttpRequest();
xhr.open("GET", "foods.txt", true);

xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // insert the response header set into pre
        pre.innerHTML = this.getAllResponseHeaders();
    }
}

xhr.send();

Live Example