« Creating a "Loading..." Animation Page with ColdFusion | Main | Best Practices for Online Credit Card Security »

Problems with browser-cached charts in ColdFusion

After adding some charts to the result pages of our tools with CF7's new <cfchart> tag, my boss reported an annoying behavior that he observed: if he clicked the browser's back button to go back to a previous result page, the chart wouldn't appear. Instead, he'd get an placeholder graphic with an error message about the chart having expired from ColdFusion's cache. What to do?

I tried increasing the timeout of the chart cache to no avail-- my boss seemed intent on hitting the back button after longer and longer intervals. Then I found a great source of information on cfchart at http://cfchart.blogspot.com/ which suggested a technique of writing the chart out to a file:

<cfchart format="png" name="calcChart" chartheight="270" chartwidth="360">
	<cfchartseries type="bar" seriescolor="##539853" serieslabel="Net Proceeds">
		<cfloop list="#variables.sortedKeyList#" index="key">
		<cfchartdata item="#stCalc[key].title#" value="#stCalc[key].net#">
		</cfloop>
	</cfchartseries>
</cfchart>

<cfset VARIABLES.chartFilename = SESSION.cfID & 'calcChart.png'>
<cffile action="write" file="/#path#/charts/#VARIABLES.chartFilename#" output="#calcChart#">

<cfoutput><img src="/charts/#VARIABLES.chartFilename#" width=360 height=270 border="0"></cfoutput>

Note that we're prepending the chart's filename with the user's session, so that one user's chart doesn't overwrite another's. This worked fantastically well, and I implemented it in all of our tools. But then after a while my boss started noticing something else that seemed odd... he would get the chart from previous runs of one tool in the results page of another. Whoops! It seemed that because the charts had the same name across tools that his browser was caching them. So, I added a random number to the chart names:

<cfset VARIABLES.chartFilename = SESSION.cfID & RandRange(1, 1000) & 'calcChart.png'>

So that's pretty much what I do for each use of <cfchart> now on the site-- to prevent it from expiring in the server's cache, I write it to the filesystem and serve it like any other image. Note that I also wrote a scheduled task to go in each night and clean out old chart files so as not to let them accumulate.

Post a comment


Type the characters you see in the picture above.