You are viewing documentation for an older version. For current documentation - click here.

FusionCharts v3 offers tremendous integration capabilities with JavaScript. You can easily use FusionCharts and JavaScript to create client side dynamic charts.

Here, we'll see the JavaScript + Url method - where we ask the chart to fetch new data from server and update itself, without incurring any page refreshes. The entire application resides in a single page which makes it a seamless experience for your end viewers.

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.

The code discussed in this example is present in Download Package > Code > ASP > DB_JS_dataURL folder.

Mission for this example

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'll assimilate both the charts in a single page and make them interact with each other using JavaScript, thereby making the end-user experience smooth. Effectively, we will do the following:

  1. Contain both the pie chart (summary) and column chart (detailed) in one page (Default.asp).
  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.asp itself.
  3. 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.
  4. 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.
  5. The updateChart() function is responsible for updating the column chart. It generates a dataURL link by including the factoryId as a part of dataURL (FactoryData.asp). FactoryData.asp is the data provider page for the detailed column chart. Once the dataURL is built, it conveys this dataURL to the column chart.
  6. The column chart would now accept this dataURL, send a request to FactoryData.asp for XML data, accept it, parse it and finally render.

Creating the charts container page

Both the charts and JavaScript functions to manipulate the charts is contained in Default.asp. It has the following code:

<%@ Language=VBScript %>
   <HTML>
    <HEAD> 
     <TITLE>FusionCharts - Database + JavaScript Example</TITLE> 
     <!-- #INCLUDE FILE="../Includes/FusionCharts.asp" -->
     <!-- #INCLUDE FILE="../Includes/DBConn.asp" --> 
     <SCRIPT LANGUAGE="Javascript" SRC="../../FusionCharts/FusionCharts.js"></SCRIPT>
     <SCRIPT LANGUAGE="JavaScript">
     /** 
      * updateChart method is invoked when the user clicks on a pie slice.
      * In this method, we get the index of the factory after which we request for XML data
      * for that that factory from FactoryData.asp, and finally
      * update the Column Chart.
      *	@param	factoryIndex Sequential Index of the factory.
      */ 
            function updateChart(factoryIndex){ 
               //DataURL for the chart
               var strURL = "FactoryData.asp?factoryId=" + factoryIndex;
               //Sometimes, the above Url and XML data gets cached by the browser.
         //If you want your charts to get new XML data on each request,
         //you can add the following line:
         //strURL = strURL + "&currTime=" + getTimeForURL();
         //getTimeForURL method is defined below and needs to be included
         //This basically adds a ever-changing parameter which bluffs
         //the browser and forces it to re-load the XML data every time.
               //URLEncode it - NECESSARY.
               strURL = escape(strURL);
               //Get reference to chart object using Dom ID "FactoryDetailed"
               var chartObj = getChartFromId("FactoryDetailed"); 
               //Send request for XML
               chartObj.setXMLUrl(strURL);
            }   
            /**
      * getTimeForURL method returns the current time 
      * in a Url friendly format, so that it can be appended to
      * dataURL for effective non-caching.
      */
            function getTimeForURL(){
               var dt = new Date();
               var strOutput = "";
               strOutput = dt.getHours() + "_" + dt.getMinutes() + "_" + dt.getSeconds() + "_" +  dt.getMilliseconds();
               return strOutput;
            }   
      </SCRIPT>
    </HEAD>
    <BODY>
    <% 
      'Initialize the Pie chart with sum of production for each of the factories 
      Dim oRs, oRs2, strQuery
      'strXML will be used to store the entire XML document generated
      Dim strXML 
      'Generate the chart element
      strXML = "<chart caption='Factory Output report' subCaption='By Quantity' pieSliceDepth='30' 
                 showBorder='1' formatNumberScale='0' numberSuffix=' Units' >" 
      'Create the recordset to retrieve data
      Set oRs = Server.CreateObject("ADODB.Recordset")
      'Iterate through each factory
        strQuery = "select * from Factory_Master"
        Set oRs = oConn.Execute(strQuery)
        While Not oRs.Eof
      'Now create second recordset to get details for this factory
        Set oRs2 = Server.CreateObject("ADODB.Recordset")
        strQuery = "select FactoryId, sum(Quantity) as TotOutput from Factory_Output where 
        FactoryId=" & ors("FactoryId") & " Group By FactoryId"
        Set oRs2 = oConn.Execute(strQuery) 
       'Generate <set label='..' value='..' link='..' />
       'Note that we're setting link as updateChart(factoryIndex) - JS Function
       strXML = strXML & "<set label='" & ors("FactoryName") & "' value='" & ors2("TotOutput") &
       "' link='javaScript:updateChart(" & oRs("FactoryId") & ")'/>"
       'Close recordset
           Set oRs2 = Nothing
           oRs.MoveNext
        Wend
        'Finally, close <chart> element
        strXML = strXML & "</chart>"
        Set oRs = nothing
        'Create the chart - Pie 3D Chart with data from strXML
        Call renderChart("../../FusionCharts/Pie3D.swf", "", strXML, "FactorySum", 500, 250, false, false)

'Column 2D Chart with changed "No data to display" message 'We initialize the chart with <chart></chart> Call renderChart("../../FusionCharts/Column2D.swf?ChartNoDataText=Please select a factory from pie chart above to view detailed data.", "", "<chart></chart>", "FactoryDetailed", 600, 250, false, false) %> </BODY> </HTML>

Before we get to the JavaScript functions, let's first see what we're doing in our ASP 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='" & ors("FactoryName") & "' value='" & ors2("TotOutput") & "' link='javaScript:updateChart(" & oRs("FactoryId") & ")'/>"

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

Call 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.

Call 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){ 
         //DataURL for the chart
         var strURL = "FactoryData.asp?factoryId=" + factoryIndex;
         //Sometimes, the above Url and XML data gets cached by the browser.
         //If you want your charts to get new XML data on each request,
         //you can add the following line:
         //strURL = strURL + "&currTime=" + getTimeForURL();
         //getTimeForURL method is defined below and needs to be included
         //This basically adds a ever-changing parameter which bluffs
         //the browser and forces it to re-load the XML data every time.
         //URLEncode it - NECESSARY.
         strURL = unescape(strURL);
         //Get reference to chart object using Dom ID "FactoryDetailed"
         var chartObj = getChartFromId("FactoryDetailed"); 
         //Send request for XML
         chartObj.setXMLUrl(strURL);
      }   

Here,

  1. We first create a dataURL string by appending the factoryID to FactoryData.asp.
  2. Thereafter, we Url Encode this dataURL.
  3. Finally, we convey this dataURL to the column chart. To do so, we first get a reference to the column chart using its DOM Id FactoryDetailed. We use the getChartFromId() function defined in FusionCharts.js to do so.
  4. Once we've the reference to the chart, we simply call the setXMLUrl method of the chart and pass it the Url to request data from.
  5. This updates the chart with new data.

If you've your chart objects inside <FORM> elements, you CANNOT use getChartFromId() method to get a reference to the chart, as the DOM Hierarchy of the chart object has changed. You'll get a JavaScript "<<ChartId>> is undefined" error. In these cases, you'll manually need to get a reference to the chart object. Or, you can opt to place the chart object outside <FORM> element.

This completes our front-end for the app. We now just need to build FactoryData.asp page, which is responsible to provide detailed data to column chart. It contains the following code:

<%@ Language=VBScript %>
      <!-- #INCLUDE FILE="../Includes/DBConn.asp" -->
      <%
   'This page is invoked from Default.asp. When the user clicks on a pie
   'slice in Default.asp, the factory Id is passed to this page. We need
   'to get that factory id, get information from database and then write XML.
   'First, get the factory Id
   Dim FactoryId
   'Request the factory Id from Querystring
   FactoryId = Request.QueryString("FactoryId")
   Dim oRs, strQuery
   'strXML will be used to store the entire XML document generated
   Dim strXML, intCounter 
   intCounter = 0
   Set oRs = Server.CreateObject("ADODB.Recordset")
   'Generate the chart element string
   strXML = "<chart palette='2' caption='Factory " & FactoryId &" Output ' subcaption='(In Units)'
              xAxisName='Date' showValues='1' labelStep='2' >"
   'Now, we get the data for that factory
   strQuery = "select * from Factory_Output where FactoryId=" & FactoryId
   Set oRs = oConn.Execute(strQuery)
   While Not oRs.Eof 
      'Here, we convert date into a more readable form for set label.
      strXML = strXML & "<set label='" & datePart("d",ors("DatePro")) 
               & "/" & datePart("m",ors("DatePro")) & "' value='" & ors("Quantity") & "'/>" 
      Set oRs2 = Nothing
      oRs.MoveNext
   Wend
   'Close <chart> element
   strXML = strXML & "</chart>"
   Set oRs = nothing
   'Just write out the XML data
   'NOTE THAT THIS PAGE DOESN'T CONTAIN ANY HTML TAG, WHATSOEVER
   Response.Write(strXML) 
%>

In this page, we basically request the factory Id passed to it as querystring, query the database for required data, build XML document out of it and finally write it to output stream.

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.