Monday, July 16, 2012

Using XMLHttpRequest.getResponseHeader to get Json Response Headers in jQuery


While developing a web page with a summary graph and a detail grid below, I needed to pass a small amount of data outside of the existing Json call data sets. I also wanted to do this without another asynchronous call back to the server. I wound up stuffing the data in a custom http response header while already on the server. This article explains how I retrieved the data on the client.

Existing Client Libraries

Both the graph and the grid were independent jQuery libraries with very specific Json response requirements. Stuffing the small amount of data in one of those response data sets could have been done with enough tinkering but I wasn’t sure how this would affect those libraries now or in future versions. While the data was related, it was also separate and I wanted the code design to reflect that.

Server Http Response Stuffing

This project uses Asp.Net MVC 4. The code to add the small amount of data should be the same across the .Net platform:

HttpContext.Response.AddHeader("RetrievalDate", this.RetrievalDate.ToShortDateString()); 

Since either Json call (the graph or the grid) will have this retrieval date, I added the additional header to one of those calls.


Make sure you set the no-cache response:

HttpContext.Response.AddHeader("Cache-Control", "no-cache"); 

Client jQuery to retrieve the Custom Json Response Header

On the client, I was using a $.getJson call to make the asynchronous call and get the data. The jqXHR parameters contains all the response headers.

jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] 

The jqXHR variable is the XMLHttpRequest object.


I wanted to be clear about the different parameters so I switched the code to use the older $.ajax style. This change moved the variable for the response headers from the initial getJSON line to the interior success invocation.


The response headers are not available until the asynchronous response successfully returns from the server so grabbing the custom response header happens in the success function:

    var request = $.ajax({
        url: uri,
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {

            // function using returned Json data
            setGraphFromData(data, chartname, title);

            // get Custom Header from Json Response
            var retrievalDate = jqXHR.getResponseHeader('RetrievalDate');

Once I have the retrievalDate, I add it to the text of my span with the same Id:
Built on:  <span id="retrievaldate"></span>


This article explains how to retrieve a header value from a Json Response using the XMLHttpRequest.getResponseHeader function.

No comments:

Post a Comment