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

Here, we will see the JavaScript + URL method - where we ask the chart to fetch new data from server and update itself, without 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 How FusionCharts XT works? and Basic Examples sections, as we will directly use a lot of concepts defined in those sections.

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

Mission for this example

Let us first define what we want to achieve in this example. We will 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 assimilate both the charts in a single page and make them interact with each other using JavaScript, thereby, smoothening the end-user experience. This is done by:

  1. Containing the pie chart (summary) and column chart (detailed) in one page (Default.php).
  2. Configuring the pie chart to use the Data String method to show summary of all factories when the page loads. This data will be built in Default.php itself.
  3. Customizing the "No data to display" message of the chart to show a friendly message. This message is required because the column chart will initialize with no data, as the user does not select a factory initially.
  4. Define the JavaScript links for each pie slice. These JavaScript links refer to the updateChart() JavaScript function present on the same page. We will later see how to manually code this function. When a pie slice is clicked, the factory ID is passed to this function.
  5. Update the column chart using the updateChart() function. It generates a dataURL link by including the factoryId as a part of dataURL (FactoryData.php). FactoryData.php is the data provider page for the detailed column chart. Once the dataURL is built, it conveys this dataURL to the column chart. The column chart now accepts this dataURL, sends a request to FactoryData.php for XML data, accepts it, parses it and finally gets rendered.
 
Creating the charts container page

The charts and JavaScript functions required to manipulate the charts is contained in Default.php. It has the following code:

<?php      
  //We have included ../Includes/FusionCharts.php and ../Includes/DBConn.php, which contains
  //functions to help us easily embed the charts and connect to a database.
   include("../Includes/FusionCharts.php");
   include("../Includes/DBConn.php");
  ?>
   <HTML>
    <HEAD> 
      <TITLE>FusionCharts XT - Database + JavaScript Example</TITLE> 
       <SCRIPT LANGUAGE="Javascript" SRC="../../FusionCharts/FusionCharts.js"></SCRIPT>
       <SCRIPT LANGUAGE="JavaScript">
      /** 
* the 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.php, and finally
* update the Column Chart.
*	@param	factoryIndex	Sequential Index of the factory.
*/ 
      function updateChart(factoryIndex){ 
      //DataURL for the chart
      var strURL = "FactoryData.php?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.
      //Get reference to chart object using Dom ID "FactoryDetailed"
      //Send request for XML
       FusionCharts("FactoryDetailed").setXMLUrl(strURL);
      }
/**
* the 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>
  <?php 
         //$strXML will be used to store the entire XML document generated
         //Generate the chart element
         $strXML = "<chart caption='Factory Output report' subCaption='By Quantity' pieSliceDepth='30' showBorder='1' formatNumberScale='0' numberSuffix=' Units' >";
         //Connect to the DB
         $link = connectToDB();
         //Fetch all factory records
        $strQuery = "select * from Factory_Master";
        $result = mysql_query($strQuery) or die(mysql_error());
         //Iterate through each factory
        if ($result) {
        while($ors = mysql_fetch_array($result)) {
        //Now create a second query to get details for this factory
        $strQuery = "select FactoryId, sum(Quantity) as TotOutput from Factory_Output where FactoryId=" . $ors['FactoryId'] . " Group By FactoryId";
        $result2 = mysql_query($strQuery) or die(mysql_error());
        $ors2 = mysql_fetch_array($result2);
        //Generate <set label='..' value='..' link='..' />
        //Note that we are setting link as updateChart(factoryIndex) - JS Function
        $strXML .= "<set label='" . $ors['FactoryName'] . "' value='" . $ors2['TotOutput'] . "' link='javaScript:updateChart(" . $ors['FactoryId'] . ")'/>";
        //Free the resultset
        mysql_free_result($result2);
        }
        }
        mysql_close($link);
        //Finally, close <chart> element
        $strXML .= "</chart>";
        //Create the chart - Pie 3D Chart with data from $strXML
        echo renderChart("../../FusionCharts/Pie3D.swf", "", $strXML, "FactorySum", 500, 250, false, true);
     //Column 2D Chart with changed "No data to display" message
     //We initialize the chart with <chart></chart>
        echo renderChart("../../FusionCharts/Column2D.swf?ChartNoDataText=Please select a factory from pie chart above to view detailed data.", "", "<chart></chart>", "FactoryDetailed", 600, 250, false, true);
        ?>
  </BODY>
</HTML>

Before we get to the JavaScript functions, let's first see what we are doing in our PHP 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 = "<set label='" . $ors['FactoryName'] . "' value='" & $ors2['TotOutput'] . "' link='javaScript:updateChart(" . $ors['FactoryId'] . ")'/>";

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

echo renderChart("../../FusionCharts/Pie3D.swf", "", $strXML, "FactorySum", 500, 250, false, true);

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.

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

Effectively, our page is now set to show two charts. The pie chart shows the summary data provided to it using Data String 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.php?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.

//Get reference to chart object using Dom ID "FactoryDetailed"
//Send request for XML
 FusionCharts("FactoryDetailed").setXMLUrl(strURL);
}

Here,

  1. We first create a dataURL string by appending the factoryID to FactoryData.php.
  2. 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 FusionCharts("FactoryDetailed") to do so.
  3. Once we have the reference to the chart, we simply call the setXMLUrl method and pass the URL to request data from.
  4. This updates the chart with new data.

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

<?php
include("../Includes/DBConn.php");
//This page is invoked from Default.php. When the user clicks on a pie
//slice in Default.php, the factory Id is passed to this page. We need
//to get that factory id, get information from database and then write XML.
//Request the factory Id from Querystring
$FactoryId = $_GET['factoryId'];
//$strXML will be used to store the entire XML document generated
//Generate the chart element string
$strXML = "<chart palette='2' caption='Factory " . $FactoryId . " Output ' subcaption='(In Units)' xAxisName='Date' showValues='1' labelStep='2' >"
//Connect to the DB
$link = connectToDB();
//Now, we get the data for that factory
$strQuery = "select * from Factory_Output where FactoryId=" . $FactoryId;
$result = mysql_query($strQuery) or die(mysql_error());
//Iterate through each factory
if ($result) {
while($ors = mysql_fetch_array($result)) {
//Here, we convert date into a more readable form for set label.
$strXML .= "<set label='" . datePart("d",$ors['DatePro']) . "/" . datePart("m",$ors['DatePro']) . "' value='" . $ors['Quantity'] . "'/>"; 
}
}
mysql_close($link);
//Close <chart> element
$strXML .= "</chart>";
//Just write out the XML data
//NOTE THAT THIS PAGE DOESN'T CONTAIN ANY HTML TAG, WHATSOEVER
echo $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 will look as under:

And when you click a pie slice, the following will appear on the same page (without involving any browser refreshes):

This example demonstrated a very basic sample of the integration capabilities possible with FusionCharts XT. For advanced demos, you can see and download our FusionCharts XT Blueprint/Demo Applications.