Collect your website visitors’ views and opinions via a Flash poll, and display the results on a Flash bar chart
Click here to download all the source files for this tutorial http://www.webdesignermag.co.uk/?page_id=85
Before we start, ask yourself this question: do you value your web visitors’ opinions and views? For example, if you have just redesigned a website that’s a customer-facing eCommerce site or social network, wouldn’t you want their opinion on the usability or the look and feel? This sort of market data has been used and gathered for many years, and used to shape the way we use sites such as Amazon and eBay today. They employ companies that specialise in this area, but for you wanting to ask a simple question then a Flash poll will do that for you, giving you the stats required to make your own judgements and decisions.
Over the next few pages, you will be creating a Flash poll that links to a MySQL database to retrieve and store the data. The results are then displayed via a bar chart to give you and your users a visual representation. We will be stepping through the tutorial and creating one, and shall then leave it up to you to decide which style you prefer. So enough chat on using polls to shape your design decisions, and let’s create one!
01 Setting the scene
Open up Flash CS3 and create a new Flash file (ActionScript 3.0). Call this file ‘barChart.fla’, open up the Property Inspector and click on Size. Set the stage to 250 x 400px and give the file a title and description. Press OK and then save.
02 Bars
Navigate to the main stage and create a new Movie Clip (F8). Call this Movie Clip ‘redbar’. Inside the Movie Clip, create a rectangle of – you guessed it – red, then create another layer under the main layer and copy the rectangle. Place it slightly to the right and a bit higher. Using that as a guide, you can then create two more layers and draw the top and side views. Delete the guide when you have completed the side and top.
03 The other bars
Now that you know how to create a 3D-style bar, do the same again but make the bars yellow, orange and blue, naming them in the same manner (‘bluebar’, etc). Place them all on the stage and align to the top and left. Open the Property Inspector and name them accordingly (‘redbar’, ‘yellowbar’, ‘orangebar’ and ‘bluebar’) in the instance name field.
04 Amounts
Create a new layer called ‘amounts’. Using the Text tool, create a Dynamic text field under each of the coloured bars. This is where the individual amount per bar will be displayed. Next up, in the Property Inspector, call the text fields ‘redres_txt’, ‘yellowres_txt’, ‘orangeres_txt’ and ‘blueres_txt’ in the instance name field.
05 Labels and headings
Create two new layers, one called ‘labels’ and the other called ‘heading’. In the heading layer, create a Static text field and place your question, ‘what colour do you prefer?’ at the top of the stage. In the labels layer, create four Static text fields and place the colour names inside. Then using the Free Transform tool, rotate by 90 degrees counterclockwise.
06 Display the totals
Next, you need to create your total text field so you can get a visual representation of the amount, which is divided into the bars’ total. Create a new layer called ‘total’ and add a Dynamic text field to the bottom of the stage. In the Property Inspector’s instance field, call it ‘total_txt’. Save your progress so far.
07 Giving some options
You have created most of the visual aspects to the poll now apart from the actual options that the user can choose from. You can do this in a number of ways, from pull-down menus to buttons. In this tutorial you will be creating buttons. Create a new layer called ‘options’ then create a button (F8). Inside the button clip, draw a red square.
08 More on buttons
Make sure the hit area is also covered by selecting and copying the square onto the hit state. Do the same for the other three colours and then navigate back to the main stage. Open the Property Inspector and call the buttons ‘red_btn’, ‘yellow_btn’, ‘orange_btn’ and ‘blue_btn’
Create your last layer in the movie and call it ‘code’. Add the import statements below, which will be used when you need to parse your data to and from the database and PHP scripts, which you will be creating in the boxout section. Now add the variables. These are initialisation variables for the bar totals and the maximum amount they can reach, so you can calculate the percentage size of the bar.
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
// vars
var max:int = 100;
var redtotal:int = 0;
var yellowtotal:int = 0;
var orangetotal:int = 0;
var bluetotal:int = 0;
10 UpdateChart function
Next, create a function that has no input or output parameters. First of all, add up the total of all the bar amounts and assign to the ‘total’ variable. Then calculate the height of each bar by taking the bar amount divided by the total of all the bars then times by the maximum amount. Do the same for all the bars and then assign the text fields the amount to display.
function updateChart():void {
// calc the amounts
var total:int = redtotal + yellowtotal +
orangetotal + bluetotal;
redbar.height = redtotal / total * max ;
yellowbar.height = yellowtotal / total * max ;
orangebar.height = orangetotal / total * max
;
bluebar.height = bluetotal / total * max ;
// set the amounts
redres_txt.text = String(redtotal);
yellowres_txt.text = String(yellowtotal);
orangeres_txt.text = String(orangetotal);
blueres_txt.text = String(bluetotal);
total_txt.text = “Total: “ + String(total);
}
11 Button code
Now you need to add a mouse click event, so that when the button is clicked it triggers a function call. In the function, remember to add the mouseEvent as a parameter. First update the total by one, and then call the functions loadData() and updateChart().
Button events
Add one to the total and update the chart
*/
red_btn.addEventListener(MouseEvent.CLICK,
onRedClick);
function onRedClick(evt:MouseEvent):void {
redtotal++;
// update database
loadData();
// update chart
updateChart();
}
yellow_btn.addEventListener(MouseEvent.CLICK,
onYellowClick);
function onYellowClick(evt:MouseEvent):void {
yellowtotal++;
// update database
loadData();
// update chart
updateChart();
}
orange_btn.addEventListener(MouseEvent.CLICK,
onOrangeClick);
function onOrangeClick(evt:MouseEvent):void {
orangetotal++;
// update database
loadData();
// update chart
updateChart();
}
blue_btn.addEventListener(MouseEvent.CLICK,
onBlueClick);
function onBlueClick(evt:MouseEvent):void {
bluetotal++;
// update database
loadData();
// update chart
updateChart();
}
12 Get the data
Using the URLLoader class, create a new loader instance and assign a constant to the dataFormat property to tell it variables will be returned. Then add a Event Listener to the loaderComplete event and call the file to load using the load method. Next, create a loaderCompleteHandler function, assign the input event.target.data and variable name to the colour totals, and finally update the chart with the new totals.
get data from database
*/
var loader:URLLoader;
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE,
loaderCompleteHandler);
loader.load(new URLRequest(“http://www.playfool.
com/magfiles/wd150/getPoll.php”));
// complete handler
function loaderCompleteHandler(event:Event):void {
yellowtotal = event.target.data.yellow;
bluetotal = event.target.data.blue;
orangetotal = event.target.data.orange;
redtotal = event.target.data.red;
// set chart at the start
updateChart();
}
13 Setting the totals
You have managed to retrieve the bar totals but you still need to set the new totals after a user has made a selection. Similar to the previous step, create a new URLLoader and an Event Listener. This time, create a new function that calls the PHP file setPoll.php, but also send variables with it using the URLVariables class. Finally, call the function buttons(), parsing in the value ‘false’.
var loaderData:URLLoader= new URLLoader();
loaderData.dataFormat = URLLoaderDataFormat.TEXT;
loaderData.addEventListener(Event.COMPLETE, d
ataLoaderComplete);
function loadData():void {
var request:URLRequest = new
URLRequest(“http://www.playfool.com/magfiles/
wd150/setPoll.php”);
var variables:URLVariables = new
URLVariables();
variables.red = redtotal;
variables.yellow = yellowtotal;
variables.orange = orangetotal;
variables.blue = bluetotal;
request.data = variables;
loaderData.load(request);
// enable all buttons
buttons(false);
}
14 More buttons
Finally for the Flash part, create the function that’s called when the setPoll.php triggers that it has completed, which will call another function called buttons(), and parse the value ‘true’. Create the function buttons and set all the buttons’ enabled property to the parsed-in parameter. This will ensure you are not clicking the buttons until the database has been updated. You’re not finished yet, though, head over to the boxout to create the PHP files.
function dataLoaderComplete(event:Event):void {
// enable all buttons
buttons(true);
}
function buttons(b:Boolean):void {
red_btn.enabled = b;
yellow_btn.enabled = b;
orange_btn.enabled = b;
blue_btn.enabled = b;
}
Update your MySQL database
Complete this tutorial by creating the PHP files to read and update the database
First of all, create a new MySQL database via your hosting control panel. This will give you the host name for the variable $Host. You can also get the other details you need from here. Create a table called ‘poll’ with four rows (red, yellow, orange and blue), all of type int.
Open up a script editor and create a new PHP file called ‘getPoll.php’. Add the script below, replacing the variables $Host, $User, $Password and $DBName with your details.
/*
Produced by Darren Richardson
for Web Designer Article
play@playfool.com
file: getPoll.php
*/
// Set up variables
$Host =”host name”;
$User = “username”;
$Password = “password”;
$DBName = “database name”;
// Set up connection string
$link = mysql_connect ($Host, $User,
$Password);
// Set the database name
mysql_select_db($DBName);
// Sql to retrieve the record if it exists ;
$sql = ‘SELECT * FROM poll’;
// get the resultset
$Result = mysql_query($sql);
// assign the variable num_rows to
the total amount
of records returned.
$num_rows = mysql_num_
rows($Result);
while ($row = mysql_fetch_
assoc($Result)) {
print ‘amt=4&’;
print ‘red=’ .$row[‘red’].’&’;
print ‘yellow=’ .$row[‘yellow’].’&’;
print ‘orange=’ .$row[‘orange’].’&’;
print ‘blue=’ .$row[‘blue’];
}
// close the database connection
mysql_close($link);
?>
The next file is setPoll.php, which takes in the four parameters parsed from Flash and updates the database with those amounts.
/*
Produced by Darren Richardson
for Web Designer Article
play@playfool.com
file: setPoll.php
*/
// Set up variables
$Host =”database host”;
$User = “username”;
$Password = “password”;
$DBName = “database name”;
// Set up connection string
$link = mysql_connect ($Host, $User,
$Password);
// Set the database name
mysql_select_db($DBName);
// create the SQL
$sql = ‘UPDATE `poll` SET red=’ .
$_REQUEST[‘red’] .
‘, yellow=’ .$_REQUEST[‘yellow’] . ‘,
orange=’
.$_REQUEST[‘orange’]. ‘, blue=’ .
$_REQUEST[‘blue’];
// set the resultset
mysql_query($sql);
// close the database connection
mysql_close($link);
?>
Upload the PHP files to the same directory location as the Flash movie on your server and you’re then ready to test your Flash poll.
No comments:
Post a Comment