NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Web Hosting

best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< September, 2010 >>
SMTWTFS
1234
567891011
12131415161718
19202122232425
2627282930
Search Blog

Recent Comments
Re: Railo 3.1 on Windows Server 2008 and IIS7 - Part 3 of 3 (by Jon at 8/27 2:04 PM)
Re: Hosts File Changes Not Acknowledged on Vista 64 (by Spacy at 8/24 3:46 PM)
Re: THE DAY CFUNITED DIED (by ComboFusion at 8/23 10:50 AM)
Re: My Grandpa (by Tasha at 8/10 4:29 PM)
Re: Just What IS a 'Service Layer', Anyway? (by dougboude at 8/02 10:10 AM)
Re: Just What IS a 'Service Layer', Anyway? (by Isaac at 8/02 2:25 AM)
Re: PayPal IPN Coldfusion CFC (by Soyestudiambre at 7/25 6:12 PM)
Re: PHP vs COLDFUSION (by Tony Garcia at 7/17 11:24 AM)
Re: PHP vs COLDFUSION (by dougboude at 7/14 8:45 AM)
Re: PHP vs COLDFUSION (by Lola LB at 7/14 5:51 AM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

16 March 2010
Leveraging Response Headers in Ajax Calls

If you're doing any sort of Ajax development, then you undoubtedly already are quite familiar with the different ways you can use an Ajax call. For instance, you can have the call return a fragment of fully formed html (such as a table populated with data). For a more advanced user, you may have your Ajax calls returning raw data in the form of JSON or XML and parse it on the client side. In either case, though, your single Ajax call is returning a single value. But what if you want several different discrete pieces of "stuff" returned in a single call? You could get creative, and do something such as this in your backend code:

<cfsetting enablecfoutputonly="true" />
<cfscript>
  stReturnData = structnew();
  stReturnData.htmlBlob = "<table><tr><td>bla bla bla</td></tr></table>";
  stReturnData.statistics = structnew();
  stReturnData.statistics.recordcount = 212;
  stReturnData.statistics.redWidgets = 32;
  stReturnData.statistics.blueWidgets = 54;
  stReturnData.someQuery = qryIRanPriorToThis;
 
  returnVal = serializeJSON(stReturnData);
</cfscript>

<cfoutput>#returnVal#</cfoutput>

The above would work perfectly fine. It would, however, require that you be willing to write some serious Javascript to access the individual pieces of data, and compels you to have to visualize how the data sets are structured and nested as a whole.

Again, nothing wrong with doing something like the above. But, when I find myself wanting to return more than one value with a single Ajax call, more often than not I will approach it by leveraging response headers.

Response headers are like the saddle bags on a Harley. If your Ajax response is the Harley, then the burley tatted dude (or dudette) riding it is your primary response value. This Harley, however, comes equipped with a pre-defined set of saddle bags that contain what I'm calling "peripheral" information, or metadata about the response, AND (this is most critical), the ability for you to add your own custom saddle bags before the response comes riding home to its caller!

I have never had a need to even look at or care about those pre-canned response headers. They contain name value pairs such as "Transfer-encoding:chunked", "content-type:text-html", "Date: Tue, 16 Mar 2010 15:43:35 GMT", and a couple of others. But, in order to satisfy needs such as I described above in the code sample, I DO add my own response headers and stuff them with values my Javascript needs.

Doing this in Coldfusion is very simple and easy (as are most tasks). Re-doing the example above, then, I'm going to choose one of the values to be my burley tatted rider (typically the value consuming the most bytes), and designate the rest to response headers, like so:

<cfsetting enablecfoutputonly="true" />

<cfset ReturnData = "<table><tr><td>bla bla bla</td></tr></table>" />

<cfheader name="recordcount" value="212" />

<cfheader name="redWidgets" value="32" />

<cfheader name="blueWidgets" value="54" />

<cfheader name="someQuery" value="#serializeJSON(qryIRanPriorToThis,true)#" />

<cfoutput>#ReturnData#</cfoutput>

So now my Harley has several new, custom saddle bags attached, each containing the value I set in the "value" attribute of the cfheader tag, and my main rider, or the actual response value is my ReturnData (the blob of html).

Let's look at the Javascript needed to utilize this response. In this example we are going to use the Prototype library to create a new Ajax Updater. Updaters simplify the task of making an Ajax call and stuffing the response value directly into a target element. So let's say we have a div with an ID 'dataDiv' that will hold a table of data. The Ajax updater line will look like this:

new Ajax.Updater('dataDiv',getDataURL,{parameters:params,method:'get');

 

 

Now, the line above deals exclusively with the response value and ignores anything to do with the response headers. In order to access those headers, we have to tell our Updater to pass its response (Harley, rider, saddlebags, and all) to a function that we designate. This is called "using a callback function", and our line of code will now look like this:

new Ajax.Updater('dataDiv',getDataURL,{parameters:params,method:'get',onComplete:processSaddlebags);

 

 

The Updater will update its target div with the response value, then hand the Harley off to the processSaddlebags function, which will look something like this:

function processSaddlebags(ajaxResponse){
  //let's set each of our response header values to a local variable...
  var recordcount = ajaxResponse.getHeader('recordcount');
  var redWidgets = ajaxResponse.getHeader('redWidgets');
  var blueWidgets = ajaxResponse.getHeader('blueWidgets');
  var objQuery = ajaxResponse.getHeader('someQuery');

  //now we can do 'stuff' with these values!
  alert('total number of records in our query: ' + objQuery['ROWCOUNT']);
  //etc....
}

It should be noted at this point that a most MAHVELOUS way for you to get a clearer picture of what is happening when your code makes Ajax calls is to use the Firefox browser with the Firebug plugin. By doing this simple thing, Firebug will provide you with all the details of every Ajax call you make. Here's a screenshot of a sample Ajax call and the kinds of info you get back (notice the custom header 'total' that I added, and the fact that I'm outputting that value in the html as the "Total Records" value):

response headers

screenshot of firebug ajax call showing response headers

response value

screenshot of firebug ajax call showing the response value

Now, all that having been said, there are size limitations to the usage of response headers that you should keep in mind. I could not find a specific reference that talked about the size limit of response headers, but I did do some experimentation to try and approximate what that limit is. I stuffed as many characters as I could into a response header, and the value was truncated at 6,653 characters (including spaces). I created two custom headers with the same 6,653 characters in it, and both were returned, so I'm assuming the limitation is per header (though common sense tells me there is probably a cumulative maximum size as well). Knowing that there IS a limit, my recommendation is that you use headers for smaller pieces of data and never to convey something as large as a JSON data set unless you know that it will be limited in size.

That's it boys and girls! Now go out there and leverage those response headers!




Posted by dougboude at 12:47 PM | PRINT THIS POST! |Link | 2 comments
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: Leveraging Response Headers in Ajax Calls
I've used headers to post things to the server with jQuery, but I've never used them to return values - this is pretty clever!
Posted by Ben Nadel on March 30, 2010 at 2:20 PM

Re: Leveraging Response Headers in Ajax Calls
@Ben - lol...and I'VE never used headers to post values to my ajax calls! It never even occurred to me to do so, but I'll definitely keep that in mind for future development. :)
Posted by dougboude on March 30, 2010 at 4:06 PM

Name:   Required
Email:   Required your email address will not be publicly displayed.

Want to receive notifications when new comments are added? Login/Register for an account.

Time to take the Turing Test!!!

2 plus 13 equals
Type in the answer to the question you see above:

Your comment:

Sorry, no HTML allowed!