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, we will see how to provide updated XML data to chart using JavaScript functions. The chart will simply accept that XML data and then 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
"Plotting from Database Example", 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 > SampleApp > app > controllers > fusioncharts > db_js_controller.rb.
View : Download Package > Code > RoR > SampleApp > app > views > fusioncharts > db_js folder.
Let us first define what we want to achieve in this example. We'll carry on from our previous drill-down example and convert it into a single page example. In our previous example, we were showing the Production Summary of all the factories in a pie chart. When the user clicked on a pie slice, he was taken to another page, where a detailed date-wise chart was shown for the required factory.
In this example we will put both the charts together on a single page where clicking on a pie slice of the Production Summary chart will open the detailed chart on the same page without page refresh.
Effectively, we will do the following:
- Contain both the pie chart (summary) and column chart (detailed) in one page (default).
- When the page loads, the pie chart would use dataXML method to show summary of all factories. This data will be built in factories_quantity builder.
- There will be a JavaScript array named data in this page. This array will contain detailed data for the factories. The array will be dynamically built by the controller and then outputted as JavaScript code.
- 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.
- The column chart would initialize with no data, as there is no factory selected initially. We'll customize the "No data to display" message of the chart to show a friendly message.
- 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 factoryID and factoryName are passed to this function.
- The updateChart() function is responsible for updating the column chart. It generates the XML data from data stored in JavaScript data array and conveys it to the column chart using the updateChartXML method.
- The column chart would now accept this XML data, parse it and finally render.
We will first take a look at the controller action default.
Controller: Fusioncharts::DbJsController
Action: default
def default
headers["content-type"]="text/html";
@factory_data = []
@js_var_string =""
index_count = -1
factory_masters = FactoryMaster.find(:all)
factory_masters.each do |factory_master|
total=0.0
index_count = index_count + 1
factory_id = factory_master.id
factory_name = factory_master.name
@js_var_string =@js_var_string+ "data[" + index_count.to_s + "] = new Array();\n" ; factory_master.factory_output_quantities.each do |factory_output|
date_of_production = factory_output.date_pro
formatted_date = format_date_remove_zeroes(date_of_production)
quantity_number = factory_output.quantity
total = total + factory_output.quantity
@js_var_string =@js_var_string+ "\t\t\t\tdata[" + index_count.to_s + "].push(new Array('" + formatted_date + "','" +quantity_number.to_s+"'));\n"
end
@js_var_string =@js_var_string+"\t\t\t";
@factory_data<<{:factory_index=>index_count,:factory_name=>factory_name,:factory_output=>total}
end
end
Most of the code in the controller is the same. The changed portions have been highlighted above.
- Perform a find on the Model FactoryMaster to select all the columns.
- Iterate through the recordset obtained above and obtain the factory id and name. Also a variable index_count which starts with 0 is incremented in the beginning of this loop. This number is used as an index for this factory in the javascript array which we will create.
- For each factory, iterate through the factory_output_quantities and calculates the total quantity for this factory. Also, create a variable @js_var_string to which
"data[" + index_count.to_s + "].push(new Array('" + formatted_date + "','"+quantity_number.to_s+"'));"
is appended. This js_var_string when output to html, creates a code to construct the 2-dimensional javascript array data. data[0], say,will contain an array with date of production and quantity values for a particular factory. So on, for all other factories.
- Constructs a hash containing index_count, factory name and total output.
- Appends the hash to the array @factory_data.
This array @factory_data is used by the view to generate the first chart. The @js_var_string is used in the view to create the javascript array. This is shown below:
View: default.html.erb
<HTML>
<HEAD>
<TITLE>FusionCharts Free - Client Side Dynamic Chart (using Database) Example</TITLE>
<%
%>
<%= javascript_include_tag "FusionCharts" %>
<%
%>
<SCRIPT LANGUAGE="JavaScript">
<%
%>
var data = new Array();
<%
%>
<%= @js_var_string %>
<%
%>
function updateChart(factoryIndex,factoryName){
var FC_ColorCounter=0;
var arr_FCColors= new Array("1941A5" , "AFD8F8", "F6BD0F", "8BBA00", "A66EDD", "F984A1", "CCCC00", "999999", "0099CC", "FF0000", "006F00",
"0099FF", "FF66CC", "669966", "7C7CB4", "FF9933", "9900FF", "99FFCC", "CCCCFF", "669900");
var strXML = "<graph caption='" + factoryName + " Output ' subcaption='(In Units)' xAxisName='Date' decimalPrecision='0'>";
var i=0;
for (i=0; i<data[factoryIndex].length; i++){
strXML = strXML + "<set name='" + data[factoryIndex][i][0] + "' value='" + data[factoryIndex][i][1] + "' color='"+ arr_FCColors[++FC_ColorCounter % arr_FCColors.length] +"' />";
}
strXML = strXML + "</graph>";
updateChartXML("FactoryDetailed",strXML);
}
</SCRIPT>
<style type="text/css">
<!--
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
.text{
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
-->
</style>
</HEAD>
<BODY>
<CENTER>
<h3><a href="http://www.fusioncharts.com" target="_blank">FusionCharts Free</a> Database + JavaScript Example</h2>
<h5>Inter-connected charts - Click on any pie slice to see detailed
chart below.</h4>
<p>The charts in this page have been dynamically generated using
data contained in a database. We've NOT hard-coded the data in
JavaScript.</p>
<%
str_xml = render "fusioncharts/db_js/factories_quantity", {:factory_data=>@factory_data}
render_chart '/FusionCharts/FCF_Pie3D.swf', '', str_xml, 'FactorySum', 650, 300, false, false do-%>
<% end-%>
<BR>
<%
render_chart '/FusionCharts/FCF_Column2D.swf?ChartNoDataText=Please click on a pie slice above to view detailed data.', '',
'<graph></graph>','FactoryDetailed', 600, 300, false, false do-%>
<% end-%>
<BR>
<BR>
<a href='/NoChart.html' target="_blank">Unable to see the charts above?</a>
<BR><h5><%= link_to '« Back to list of examples', :controller=>'fusioncharts/index'%></h5>
</CENTER>
</BODY>
</HTML>
In this page, we first render all the data in database as JavaScript array. To do so, output the variable that is present in the controller @jsVarString in the <SCRIPT> section of <HEAD> tag as shown.
var data = new Array();
<%= @jsVarString %>
If you run this page and view the source JavaScript code, you'll see the following: var data = new Array();
data[0] = new Array();
data[0].push(new Array('01/01','21'));
data[0].push(new Array('02/01','23'));
data[0].push(new Array('03/01','22'));
data[0].push(new Array('04/01','24'));
data[0].push(new Array('05/01','32'));
data[0].push(new Array('06/01','21'));
data[0].push(new Array('07/01','34'));
data[0].push(new Array('08/01','32'));
data[0].push(new Array('09/01','32'));
data[0].push(new Array('10/01','23'));
data[0].push(new Array('11/01','23'));
data[0].push(new Array('12/01','32'));
data[0].push(new Array('13/01','53'));
data[0].push(new Array('14/01','23'));
data[0].push(new Array('15/01','26'));
data[0].push(new Array('16/01','43'));
data[0].push(new Array('17/01','16'));
data[0].push(new Array('18/01','45'));
data[0].push(new Array('19/01','65'));
data[0].push(new Array('20/01','54'));
data[1] = new Array();
data[1].push(new Array('01/01','121'));
data[1].push(new Array('02/01','123'));
data[1].push(new Array('03/01','122'));
data[1].push(new Array('04/01','124'));
data[1].push(new Array('05/01','132'));
data[1].push(new Array('06/01','121'));
data[1].push(new Array('07/01','134'));
data[1].push(new Array('08/01','132'));
data[1].push(new Array('09/01','132'));
data[1].push(new Array('10/01','123'));
data[1].push(new Array('11/01','123'));
data[1].push(new Array('12/01','132'));
data[1].push(new Array('13/01','153'));
data[1].push(new Array('14/01','123'));
data[1].push(new Array('15/01','126'));
data[1].push(new Array('16/01','143'));
data[1].push(new Array('17/01','116'));
data[1].push(new Array('18/01','145'));
data[1].push(new Array('19/01','165'));
data[1].push(new Array('20/01','154'));
data[2] = new Array();
data[2].push(new Array('01/01','54'));
data[2].push(new Array('02/01','56'));
data[2].push(new Array('03/01','89'));
data[2].push(new Array('04/01','56'));
data[2].push(new Array('05/01','98'));
data[2].push(new Array('06/01','76'));
data[2].push(new Array('07/01','65'));
data[2].push(new Array('08/01','45'));
data[2].push(new Array('09/01','75'));
data[2].push(new Array('10/01','54'));
data[2].push(new Array('11/01','75'));
data[2].push(new Array('12/01','76'));
data[2].push(new Array('13/01','34'));
data[2].push(new Array('14/01','97'));
data[2].push(new Array('15/01','55'));
data[2].push(new Array('16/01','43'));
data[2].push(new Array('17/01','16'));
data[2].push(new Array('18/01','35'));
data[2].push(new Array('19/01','78'));
data[2].push(new Array('20/01','75'));
Now, before we get to the JavaScript functions, let's first see what we're doing in our RoR code. In the body of the html, we have rendered two charts. The first chart uses the builder template factory_quantities.builder, passes the @factory_data array constructed in the controller to it. The resulting xml is passed to render_chart function to show a Pie3D chart.
The second chart is initialized with a customized message "Please select a factory from pie chart above to view detailed data.".
Let us take a look at the builder which actually does the work of creating a link to the detailed chart for each factory.
xml = Builder::XmlMarkup.new
xml.graph(:caption=>'Factory Output report', :subCaption=>'By Quantity',:decimalPrecision=>'0' ,:showNames=>'1' ,:numberSuffix=>' Units' ,:pieSliceDepth=>'20' ,:formatNumberScale=>'0' ) do
for item in factory_data
xml.set(:name=>item[:factory_name],:value=>item[:factory_output],:link=>'javaScript:updateChart('+item[:factory_index].to_s+
',"'+item[:factory_name]+'");' )
end
end
For each <set>, we provide a JavaScript link to the updateChart() function and pass the factory index and factory name to it.
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 index of the factory in the array and the factory name of the pie is passed to it. This function is responsible for updating the column chart and contains the following code:
function updateChart(factoryIndex,factoryName){
var FC_ColorCounter=0;
var arr_FCColors= new Array("1941A5" , "AFD8F8", "F6BD0F", "8BBA00", "A66EDD", "F984A1", "CCCC00", "999999", "0099CC", "FF0000", "006F00",
"0099FF", "FF66CC", "669966", "7C7CB4", "FF9933", "9900FF", "99FFCC", "CCCCFF", "669900");
var strXML = "<graph caption='" + factoryName + " Output ' subcaption='(In Units)' xAxisName='Date' decimalPrecision='0'>";
var i=0;
for (i=0; i<data[factoryIndex].length; i++){
strXML = strXML + "<set name='" + data[factoryIndex][i][0] + "' value='" + data[factoryIndex][i][1] + "' color='"+ arr_FCColors[++FC_ColorCounter % arr_FCColors.length] +"' />";
}
strXML = strXML + "</graph>";
updateChartXML("FactoryDetailed",strXML);
}
Here,
- We first create the XML data document for the column chart by iterating through data contained in our JavaScript data array, by using the index of the factory provided as parameter.
- Thereafter, we pass 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.
- Once we've the reference to the chart, we simply call the updateChartXML method of the chart and pass the chart id and XML data document as parameters.
- 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 Free. For advanced demos, you can see and download our FusionCharts Blueprint/Demo Applications. |