Charting data from a database using Adobe Flex and PHP

DZone 's Guide to

Charting data from a database using Adobe Flex and PHP

· Web Dev Zone ·
Free Resource

Creating charts and data visualization is one of the areas where Adobe Flash shines. The combination of a very powerful drawing API that makes it easy to generate artwork and the interactivity means that Flash is ideally suited for integrating data visualizations. It used to be that you'd have to be very familiar with Flash and scripting to work with charting. There are some great Flash charting libraries out there but they often cost money or don't allow you to fully customize the look and feel of the charts.


Introducing Flex

Adobe Flex Software was created with developers in mind. Flex applications run on the Flash Player (or AIR) so you get the benefits of Flash's reach while having a tool and language that is specifically for developers. You use a combination of XML-markup and scripting to create applications. Further, you can use CSS syntax to customize the look and feel of the charts. Flex makes it straightforward to add interactive charts to web applications.


Bringing Data Into Flex

Flex can't talk directly to a database so it relies on a 3rd party server to consume data. Flex can just grab XML data or SOAP-based web services but if you are using PHP you can use a protocol called AMF which packages data into a lightweight, binary format that is ideal for large data sets. Flash Builder 4 includes a set of data wizards that help you get started. In this case I have MAMP installed with some PHP classes that expose National Forest Service data. With Flash Builder 4 I can set my application up to call that data so I can chart it.

Start by creating a new project and be sure to set the server type to PHP. At the next screen set the server configuration options. The server information is required for Flex to make a link with the server so that the PHP classes can be called directly. When that's done you can click Finish and Flash Builder will generate the skeleton project.



Select the Data menu and choose "Connect to PHP". That brings up the PHP Service configuration. Make sure the PHP files are in a web-accessible location and then select the ForestAcreService. The wizard automatically fills in the default naming conventions for you and clicking next will show a list of the PHP functions that are available. After that, click Finish and Flash Builder will automatically generate the code needed to connect to the PHP classes. 



It's easy to make sure everything is working by right clicking the method name in the Data/Services panel and selecting Test Operation. You can then call the method directly from Flash Builder and make sure the result comes back correctly. The last step is to define a data type for the result data. Right click on the getAllForestAcres method and select "Configure Return Type". Then just select the auto-detect option and Flash Builder will call the method and then provide the option to create a custom data type based on the class name with the properties from the database. In this case it matches exactly with the PHP data type from the server.



Charting the Data

When using the data wizards it is easy to start charting data by using design view. Then the chart can be customized and refined using code. First, switch from source view to design view if Flash Builder isn't already in it. There should be a components panel with a list of components grouped into folders. Scroll to the bottom category, labeled Charts, and then drag an AreaChart to the design view panel. Give it an id and a chart with some dummy data will be rendered on the screen. The property panel can be used to change the x/y position and size of the chart. I changed mine to x/y = 0 and width and height set to 100% each. 

To populate the chart with data from the database simply drag the getAllForestAcres() method from the Data/Services panel to the chart in design mode. A dialogue box will appear to both generate the service call as well as associate the result with the chart. For this method set the Y-field to total_acres and set the X axis field to year and click OK.



The chart won't automatically update but if you run the application you'll see the data rendering from the database. Hovering over the chart gives you a detailed view of the data points. Up to now if the properties for width/height are set to 100% the application is taking up the whole page. In a lot of cases the SWF file showing the chart would be embedded in a page with HTML content around that. To do that, start by setting the width to 500 and the height to 300 and remove the minWidth and midHeight properties so the application tag looks like this:

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
width="500" height="300"


When the application runs now the chart will be smaller and in the center top of the page. You can start adding HTML content around it. 


Modifying Flash Builder's HTML

Flash Builder uses a series of templates to generate the files for viewing the chart. When the chart is run in the browser, it's actually an HTML page and a series of JavaScript files that then embed the SWF file and display it. When the SWF file is set to specific height/width, the SWF is just embedded on the page and whatever is in the templates will render in the final HTML file. 

Open up the index.template.html page inside the html-template directory. Inside are a bunch of script references and the embed tag. There are also variables, indicated by the ${} that change based on information set inside of the application tags. 

Add the following line between the end of the noscript tag and the end of the body tag near the end of the page:

<p>Toggle Data</p>


Running the application now shows that text below the SWF file.


Using the Flex/AJAX Bridge

It's important to be able to update Flash content from HTML when using this configuration. Flash Builder offers a way to generate the code to expose functions in the Flex application to HTML content. 

Back in the main MXML file, add the following function to the script blog. 

protected function external_clickHandler(event:MouseEvent):void
if(areaSeries.yField == "total_acres")
areaSeries.yField = "total_national_forests";
} else {
areaSeries.yField = "total_acres";


There are two sets of data from the database. One shows the total amount of acreage by year and the other shows the total number of national forests by year. This function toggles between the two. 

Now right click on the project folder and select Create Ajax Bridge. This brings up a screen where specific functions or properties can be selected to expose to the HTML page. Select the external_clickHandler function and click OK.



This generates both the Flash code and a sample of HTML/JS code a folder called AjaxBridge. In the lib folder of that directory is a file called FABridge.js. Copy that file and the InteractiveChartsWithPHP.js file to the html-template directory.

Go back to the index.template.html file. The first thing to do is to add the two external JavaScript files to the index file. Add the following lines below the script tag with a src of swfobject.js:

<script type="text/javascript"src="FABridge.js"></script>
<script type="text/javascript"src="InteractiveChartsWithPHP.js"></script>

The last step to make the AjaxBridge work is to call it when the user clicks on the text. To do this, just call the function using the APIs from the FABridge.js file. 

<p><ahref="#"onclick="b_InteractiveChartsWithPHP_root.external_clickHandler()">Change Data</a></p>


Animating the Chart

The last step is optional but shows how to add some animation to the chart. Flex has a few default hooks for animating data when it changes on a chart. There are a number of series transitions that can be used including the slide, interpolate, and zoom. Those effects can be tweaked to create various animations when the data changes. In this case, SeriesSlide can be added to do a left to right wipe when the chart displays or changes data.

Add the following lines inside of the Declarations tags:

<mx:SeriesSlide id="slideIn" duration="500" direction="up" />
<mx:SeriesSlide id="slideOut" duration="500" direction="down" />


Now the chart needs to be modified so that the effects can be applied to an change in data. To do this, add a couple of showData properties to the AreaSeries tag:

<mx:AreaChart x="0" y="0" id="areachart1" width="100%" height="100%"
dataProvider="{getAllForestAcresResult.lastResult}" showDataTips="true">


And that's all there is to it. That provides an overview of how to get started with charting in Flex and then manipulate that chart in an HTML environment. 


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}