OpenFlashChart — loading data via javascript

OFC2 sample chart

I’m just getting started using OFC2 to render charts for a project.  I specifically want to include all the data in the initial page load, rather than require another request to the server (the standard way to do it w/ OFC2).  The library provides a mechanism for this, but it is described as hard, ‘for advanced users only‘.  After slogging through it for a few hours today, I finally arrived at the key.

The data to be loaded in to a chart has to be passed to the OFC2 swf object as a JSON string (not a javascript object).  The OFC2 download package includes the json2.js javascript library to create JSON string from objects.  The problem is, it produces bad output.

Just as example, here a simple javascript object that defines a basic OFC2 bar chart (the image at the start of this post):

var d = { elements: [{type:'bar_glass',values:[1,2,4,8,4,2,1]}],
title: { text: "test data" } };

JSON.stringify(d) produces the following:

{"elements":"[{\"type\": \"bar_glass\", \"values\": [1, 2, 4, 8, 4, 2, 1]}]","title":{"text":"test data"}}

The array value for “elements” was turned into a quoted string.  When this JSON is parsed, it will be interpreted as a quoted string, not an array.  Fail.

The latest OFC2 version as of this writing (Lug Wyrm Charmer) contains a json2.js version dated 2008-03-24.  The latest version from is dated 2009-09-29, but it’s still broken.  Use a better javascript library, such as prototype — In my testing, using the Object.toJSON() method from prototype instead of JSON.stringify() worked perfectly.

So here’s a full working example (apologies for the formatting):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>ofc test</title>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "250", "200", "9.0.0",
"expressInstall.swf", {"get-data":"load_data"});

function load_data() {
var data = { elements: [{type:'bar_glass',values:[1,2,4,8,4,2,1]}],
title: { text: “test data” } };
return Object.toJSON(data);
<div id=”my_chart”></div>