In our previous example, we had combined FusionCharts, Ruby and JavaScript to create client side dynamic charts. We were updating the chart by asking it to fetch new data from server and update itself, without incurring any page refreshes.

In this example, instead of asking the chart to get XML data from server, we'll provide updated XML data to chart using JavaScript functions. The chart will simply accept that XML data and render.

This method can effectively be used in your AJAX applications, where your JavaScript code gets the updated XML from server and then provides it to charts locally. You can process the data received from AJAX Calls, build XML from it and finally provide it to the chart.

Before you proceed with the contents in this page, we strictly recommend you to please go through the sections "How FusionCharts works?" and "Basic Examples", as we'll directly use a lot of concepts defined in those sections.

All code discussed here is present in
Controller : Download Package > Code > RoR > app > controllers > db_js_controller.rb.
Rhtml : Download Package > Code > RoR > app > views > db_js folder.
 
Defining the applicaton

We'll carry on from our previous "Ruby, JavaScript and dataURL" example and convert it to use JavaScript + XML, so that the new XML is provided to the chart using JavaScript functions - the charts NO more directly request data from server. To attain this, we send all the pertinent data from our server to the end viewer as JavaScript arrays in the same page. The JavaScript arrays are dynamically generated by Ruby pages at run-time and filled with data.

Effectively, we will do the following:

  1. Contain both the pie chart (summary) and column chart (detailed) in one page (Default).
  2. When the page loads, the pie chart would use dataXML method to show summary of all factories. This data will be built in default itself.
  3. There will be a JavaScript array named as data in this page. This array will contain detailed data for the factories. The array will be dynamically built using Ruby and then outputted as JavaScript code.
  4. Apart from the data in JavaScript, we'll also have a local JavaScript function updateChart(), which would process the data in this array and convert it to XML data document, for direct usage by the column chart.
  5. The column chart would initialize with no data, as the user has not selected a factory initially. We'll customize the "No data to display" message of the chart to show a friendly message.
  6. The pie chart would have JavaScript links defined for each pie slice. This JavaScript links refer to updateChart() JavaScript function present on the same page. We'll later see how to hand code this function. When a pie is clicked, the factory ID is passed to this function.
  7. The updateChart() function is responsible for udapting the column chart. It generates the XML data from data stored in JavaScript data array and conveys it to the column chart.
  8. The column chart would now accept this XML data, parse it and finally render.
 
Creating the page
Both the charts and JavaScript functions to manipulate the charts has the following code:


Controller: db_js_controller.rb
Action: index

class DbjsController < ApplicationController
 def index
   @jsVarString1 = ""
   #Database Objects oRs, oRs2, strQuery, indexCount
   indexCount = 0
   oRs = Factorymaster.find(:all)
   oRs.each do |recordset1|
     indexCount = indexCount + 1
     #Create JavaScript code to add sub-array to data array
     #data is an array defined in JavaScript (see below)
     #We've added \t + \n to data so that if you View Source of the
     #output HTML, it will appear properly. It helps during debugging

     @jsVarString1 = @jsVarString1 + "\t \t"+ "data[" + indexCount.to_s + "] = new Array();" + "\n"
     oRs2 = Factoryoutput.find(:all,:conditions=>["FactoryId=?",recordset1.FactoryId.to_s], :order => 'DatePro ASC')
     oRs2.each do |recordset2|
       #Put this data into JavaScript as another nested array.
       #Finally the array would look like data[factoryIndex][i][dataLabel,dataValue]

       @jsVarString1 = @jsVarString1 + "\t \t" + "data[" + indexCount.to_s + "].push(new Array('" + recordset2.DatePro.strftime('%d')        + "/" + recordset2.DatePro.strftime('%m') + "'," + recordset2.Quantity.to_s + "));" + "\n"
     end
   end
   #Initialize the Pie chart with sum of production for each of the factories
   #strXML will be used to store the entire XML document generated

   strXML =''
   #Re-initialize Index
   indexCount=0
   #Generate the chart element
   strXML = "<chart caption='Factory Output report' subCaption='By Quantity'    pieSliceDepth='30' showBorder='1'    formatNumberScale='0' numberSuffix=' Units' >"
   #Move back to first index of the factory master recordset
   oRs.each do |recordset1|
     #Update index count - sequential
     indexCount = indexCount + 1
     @oRs2 = Factoryoutput.find(:all,:conditions=>["FactoryId=?",recordset1.FactoryId.to_s])
     recordcount = @oRs2.length
     count = 0
     quantity = 0
     while count < recordcount
       quantity = quantity + @oRs2[count][:Quantity].to_i
       count = count + 1
     end
     #puts quantity
     #Generate <set label='..' value='..'/>

     factoryid = ""
     @oRs2.each do |recordset2|
       if factoryid != recordset2.FactoryId
         strXML = strXML + "<set label='" + recordset1.FactoryName + "' value='" + quantity.to_s + "' link='javaScript:updateChart(" + indexCount.to_s + ")'/>"
       end
       factoryid = recordset2.FactoryId      
     end
   end
   #Finally, close <chart> element
   strXML = strXML + "</chart>"
   #Create the chart - Pie 3D Chart with data from strXML
   @chart1= renderChart("/FusionCharts/Pie3D.swf", "", strXML, "FactorySum", 500, 250, false, false)
   @chart2=renderChart("/FusionCharts/Column2D.swf?ChartNoDataText=Please select a factory from pie chart above to view detailed data.", "", "<chart></chart>", "FactoryDetailed", 600, 250, false, false)

 end
end


View:
<HTML>
 <HEAD>
  <TITLE>FusionCharts - Form Based Data Charting Example</TITLE>
  <SCRIPT LANGUAGE="Javascript" SRC="/FusionCharts/FusionCharts.js">    
  </SCRIPT>
  <SCRIPT LANGUAGE="Javascript" >
    //Here, we use a mix of server side script (Ruby) and JavaScript to
    //render our data for factory chart in JavaScript variables. We'll later
    //utilize this data to dynamically plot charts.
    //All our data is stored in the data array. From Ruby, we iterate through
    //each recordset of data and then store it as nested arrays in this data array.

    var data = new Array();
    <%= @jsVarString1%>
    <%
    #The data is now present as arrays in JavaScript. Local JavaScript functions
    #can access it and make use of it. We'll see how to make use of it.
    %>
    /**
    * updateChart method is invoked when the user clicks on a pie slice.
    * In this method, we get the index of the factory, build the XML data
    * for that that factory, using data stored in data array, and finally
    * update the Column Chart.
    * @param factoryIndex Sequential Index of the factory.
    */    

    function updateChart(factoryIndex){
      //Storage for XML data document
      var strXML = "<chart palette='2' caption='Factory " + factoryIndex + " Output ' subcaption='(In Units)' xAxisName='Date' showValues='1' labelStep='2' >";
      //Add <set> elements
      var i=0;
      for (i=0; i< data[factoryIndex].length; i++){
      strXML = strXML + "<set label='" + data[factoryIndex][i][0] + "' value='" + data[factoryIndex][i][1] + "' />";
      }
    //Closing Chart Element
    strXML = strXML + "</chart>";
    //Get reference to chart object using Dom ID "FactoryDetailed"
    var chartObj = getChartFromId("FactoryDetailed");
    //Update it's XML
    chartObj.setDataXML(strXML);
    }
   </SCRIPT>
  <style type="text/css">  
 </HEAD>
 <BODY>   
   <%= @chart1%>
   <%
    #Column 2D Chart with changed "No data to display" message
    #We initialize the chart with <chart></chart>%>
   <%= @chart2%>
 </BODY>
</HTML>

In this page, before rendering any HTML code, we first generate all the data in database as JavaScript array. To do so, we use string concatenation in Ruby variables to store all data as JavaScript array code. Once the JavaScript code is built in our Ruby variable, we write it out in the <SCRIPT> section of HTML <HEAD>.

<SCRIPT LANGUAGE="JavaScript">
  var data = new Array();
    <%= @jsVarString1%>
</SCRIPT>

If you run this page and view the source JavaScript code, you'll see the following:

var data = new Array();

data[1] = new Array();
data[1].push(new Array('1/1',21));
data[1].push(new Array('2/1',23));
data[1].push(new Array('3/1',22));
data[1].push(new Array('4/1',24));
data[1].push(new Array('5/1',32));
data[1].push(new Array('6/1',21));
data[1].push(new Array('7/1',34));
data[1].push(new Array('8/1',32));
data[1].push(new Array('9/1',32));
data[1].push(new Array('10/1',23));
data[1].push(new Array('11/1',23));
data[1].push(new Array('12/1',32));
data[1].push(new Array('13/1',53));
data[1].push(new Array('14/1',23));
data[1].push(new Array('15/1',26));
data[1].push(new Array('16/1',43));
data[1].push(new Array('17/1',16));
data[1].push(new Array('18/1',45));
data[1].push(new Array('19/1',65));
data[1].push(new Array('20/1',54));
data[2] = new Array();
data[2].push(new Array('1/1',121));
data[2].push(new Array('2/1',123));
data[2].push(new Array('3/1',122));
data[2].push(new Array('4/1',124));
data[2].push(new Array('5/1',132));
data[2].push(new Array('6/1',121));
data[2].push(new Array('7/1',134));
data[2].push(new Array('8/1',132));
data[2].push(new Array('9/1',132));
data[2].push(new Array('10/1',123));
data[2].push(new Array('11/1',123));
data[2].push(new Array('12/1',132));
data[2].push(new Array('13/1',153));
data[2].push(new Array('14/1',123));
data[2].push(new Array('15/1',126));
data[2].push(new Array('16/1',143));
data[2].push(new Array('17/1',116));
data[2].push(new Array('18/1',145));
data[2].push(new Array('19/1',165));
data[2].push(new Array('20/1',154));
data[3] = new Array();
data[3].push(new Array('1/1',54));
data[3].push(new Array('2/1',56));
data[3].push(new Array('3/1',89));
data[3].push(new Array('4/1',56));
data[3].push(new Array('5/1',98));
data[3].push(new Array('6/1',76));
data[3].push(new Array('7/1',65));
data[3].push(new Array('8/1',45));
data[3].push(new Array('9/1',75));
data[3].push(new Array('10/1',54));
data[3].push(new Array('11/1',75));
data[3].push(new Array('12/1',76));
data[3].push(new Array('13/1',34));
data[3].push(new Array('14/1',97));
data[3].push(new Array('15/1',55));
data[3].push(new Array('16/1',43));
data[3].push(new Array('17/1',16));
data[3].push(new Array('18/1',35));
data[3].push(new Array('19/1',78));
data[3].push(new Array('20/1',75));

You can clearly see that our code has outputted JavaScript code that can now locally create an array and feed it with requisite data.

Now, before we get to the JavaScript functions, let's first see what we're doing in our Code.

We first create the XML data document for Pie chart - summary of factory output. For each <set>, we provide a JavaScript link to the updateChart() function and pass the factory ID to it as shown in the line below:

 strXML = strXML + "<set label='" + recordset1.FactoryName + "' value='" + quantity.to_s + "' link='javaScript:updateChart(" + indexCount.to_s + ")'/>"

We now render the Pie 3D chart using dataXML method. The Pie 3D chart has its DOM Id as FactorySum:

@chart1= renderChart("/FusionCharts/Pie3D.swf", "", strXML, "FactorySum", 500, 250, false, false)

Now, we render an empty Column 2D chart with <chart></chart> data initially. We also change the "No data to display." error to a friendly and intuitive "Please select a factory from pie chart above to view detailed data." This chart has its DOM Id as FactoryDetailed.

@chart2= renderChart("/FusionCharts/Column2D.swf?ChartNoDataText=Please select a factory from pie chart above to view detailed data.", "", "<chart></chart>", "FactoryDetailed", 600, 250, false, false)

Effectively, our page is now set to show two charts. The pie chart shows the summary data provided to it using dataXML method. The column chart shows the above "friendly" error message. Now, when each pie slice is clicked, the updateChart() JavaScript function is called and the factoryID of the pie is passed to it. This function is responsible for updating the column chart and contains the following code:

function updateChart(factoryIndex){
    //Storage for XML data document
    var strXML = "<chart palette='2' caption='Factory " + factoryIndex + " Output ' subcaption='(In Units)' xAxisName='Date' showValues='1' labelStep='2' >";

   //Add <set> elements
   var i=0;
   for (i=0; i<data[factoryIndex].length; i++){
      strXML = strXML + "<set label='" + data[factoryIndex][i][0] + "' value='" + data[factoryIndex][i][1] + "' />";
   }   

   //Closing Chart Element
   strXML = strXML + "</chart>";

   //Get reference to chart object using Dom ID "FactoryDetailed"
   var chartObj = getChartFromId("FactoryDetailed");
   //Update it's XML
   chartObj.setDataXML(strXML);
   }

Here,

  1. We first create the XML data document for the column chart by iterating through data contained in our JavaScript data array.
  2. Thereafter, we convery this XML data to the column chart. To do so, we first get a reference to the column chart using it's DOM Id FactoryDetailed. We use the getChartFromId() function defined in FusionCharts.js to do so.
  3. Once we've the reference to the chart, we simply call the setDataXML method of the chart and pass it the XML data document.
  4. This updates the chart with new data.

When you now see the application, the initial state would look as under:

And when you click on a pie slice, the following would appear on the same page (without involving any browser refreshes):
This example demonstrated a very basic sample of the integration capabilities possible with FusionCharts v3. For advanced demos, you can see and download our FusionCharts Blueprint/Demo Applications.