Flash Development

 


 
                                                                                                                                                     

Flash Article # 1 Building Data Drive Flash Movies

Flash Article # 2 Creating Flash Forms

Next weeks article Getting up to speed on creating Flash Animations and movies.

 

Flash Article # 1 Data Driven Movies
 

So you've figured out the basics of the Flash toolbox, created your first tween, and added some wild animation to your Web site. You've built animation clips with fading reverbs, and created buttons which change shape as you mouse over them. And you're wondering what to do next. Well, wonder no more.

While there's a lot you can do with the tools Flash gives you, it's when you hook it up to the wild and wacky world of the Web that you truly begin to appreciate the power (and genius) of the application. Today's Web is built around dynamic, data−driven Web sites, and Flash, which comes with built−in capabilities to read data from a variety of data sources, is well−suited to it.

The new data retrieval features in Macromedia Flash 5 (and better) allow developers to retrieve information from server−side databases and use this information to dynamically construct animation clips on the fly. As you might imagine, this opens up new possibilities for the creative Web developer, and sets the tone for a new generation of smart, dynamic and very cool Web applications.

In this article, I'm going to give you a little preview, demonstrating how Flash can be hooked up to a MySQL database to dynamically construct database−driven animation clips. Most of these examples are fairly simple  you might even find them *too* simple − but they should serve as a gentle introduction to the new  capabilities Flash gives you, and perhaps even help to answer that "what next?" question by sparking some ideas in that tangled web of neurons you call a brain. So strap yourself in tight − this is gonna be an exciting  ride!
 

Before we get started with building a database−driven animation clip, you need to know a little theory. The first − and most critical − thing you need to know is that there is never direct communication between Flash and a database. A Flash movie can never talk directly to a database server − there is always a third party involved. This third party takes care of building and transmitting the query from the movie to the database, and retrieving and massaging the results into a format that is usable by the movie clip. This third party's role is usually played by a server−side application such as Perl, PHP, ASP, ColdFusion et al. In order to better understand this, let's consider a simple example. Pop open Flash, create a new movie and
then create a new Graphic symbol. Name it "message".

Now, in the Symbol Editor, create a text box with the Text tool (hit A on the keyboard). Use the Window −> Panels −> Text Options panel to turn it into a dynamic, multi−line text box.

While you're there, also set a variable name for the newly−minted dynamic text box − this is the variable that Flash will look for when the time comes to populate the text box. I've used the variable name "msg".

In the timeline, select the first frame (this should be a keyframe), right−click it and pop up the Actions dialog box. On the left−hand side of the Actions panel, look in the "Basic Actions" sub−category and select the loadVariables() function. This ActionScript function allows you to load variables into the Flash movie from an external URL − more on how this works later.

The lower half of the Actions panel should prompt you to enter some parameters for this function − specifically, the URL to get the variables from. For the moment, let's assume that the variables will be loaded from the URL "message.txt" − specify this in the lower half of the panel, as shown below.

The file specified as the variable source must contain data in the MIME format
"application/x−www−urlformencoded" − that is, a series of variable−value pairs separated by ampersands (&). Here's what my copy of "message.txt" looks like: msg=Welcome to the wonderful and wacky world of dynamic data
sources!

Obviously, this file should be stored in the same place as the Flash movie (you can store it elsewhere too, just remember to alter the URL supplied to loadVariables() appropriately). Now, when the Flash movie plays, the contents of the file "message.txt" will be read, converted to variables
and used within the Flash movie. Take a look:

Wanna change the message? Just alter the contents of "message.txt",
msg=Look, Ma, no hands!
and watch in amazement as your Flash movie changes as well!

Obviously, that was a very primitive example, though one that did demonstrate the concept of integrating data from an external source with a Flash movie. Now, how about a twist?

Let's suppose I modify the Flash file above so that the call to loadVariables() loads variables from a server−side script ("message.php"), rather than a static text file. loadVariablesNum ("http://localhost/message.php", 0);
This "message.php" script contains code to retrieve a message (either from a database or other data source) and output it in the format Flash needs. Here's what the script looks like:

<?
// message.php
// open connection to database
$connection = mysql_connect("localhost", "root", "secret") or die
("Unable to connect!");
mysql_select_db("data") or die ("Unable to select database!");
// formulate and execute query
$query = "SELECT message FROM message_table";
$result = mysql_query($query) or die("Error in query: " .
mysql_error());
// get row
$row = mysql_fetch_object($result);
// print output as form−encoded data
echo "msg=" . urlencode($row−>FirstName);
// close connection
mysql_close($connection);
?>
 

This should be fairly simple to understand, even if you've never programmed in PHP before. Very simply, I'm opening a connection to a MySQL database, running an SQL query to retrieve the contents of the "message" table, and displaying that content as form−encoded data

msg=Happy+Father%27s+Day%21
Now, when you run the Flash movie, it will access the specified URL, retrieve the form−encoded
variable−value pair, parse it, and insert the variable values into the movie. Which is why the Flash movie will look like this:

Any change to the database record will be immediately reflected in the Flash file − with zero changes required to the Flash source. In case you don't want to use a database as your data source, you can even run a shell command and send the output of the command to the Flash movie for display. Consider this variant of the script above, which displays the output of the "fortune" program (a new message every time) whenever the Flash movie is played
back in your browser.
<?
$output = `/usr/games/fortune`;
echo "msg=" . urlencode($output);
?>

Now, you can develop some pretty cool applications with power like this...and one of the coolest (and easiest) is a dynamic news ticker, updated from a MySQL database. Let's see how. First, pop open a new Flash movie and create a dynamic text box symbol, in the manner described on the previous page. Call it "ticker", and name the variable which will contain the data for the text box "content".

 

 

 

 

 

 

 

Format the appearance of the text box, by adjusting the values in the Window −> Panels −> Text Options and
Window −> Panels −> Character dialog boxes. I used a white Arial font, size 12, right−aligned.

 

Next, we need to create a motion tween to move the text box horizontally across the bottom of the movie.
Insert an instance of the newly−minted "ticker" symbol into your movie clip, outside the lower right edge of
your movie clip.

Insert a new keyframe in your timeline somewhere around frame 40, and move the symbol instance all the way across to the other edge of the movie clip.

Right−click anywhere between the two keyframes in the timeline and insert a motion tween.

Test your movie. You should see the symbol instance float horizontally across the bottom of the screen. Of course, it doesn't contain anything yet − which makes it fairly useless. Let's rectify that next. Right−click the first keyframe and insert some ActionScript.

loadVariablesNum ("http://localhost/ticker.php", 0);

This tells Flash to load variables generated by the server−side script "ticker.php" into the movie, and use them wherever required. Let's look at that script next.

Let's assume that the news headlines to be displayed are stored in a database table which looks something like this:

est your movie. You should see the symbol instance float horizontally across the bottom of the screen. Of course, it doesn't contain anything yet − which makes it fairly useless. Let's rectify that next. Right−click the first keyframe and insert some ActionScript.

loadVariablesNum ("http://localhost/ticker.php", 0);

This tells Flash to load variables generated by the server−side script "ticker.php" into the movie, and use them wherever required. Let's look at that script next.

Let's assume that the news headlines to be displayed are stored in a database table which looks something like this:

+−−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−
| date | body
+−−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−|
2001−12−20 10:16:48 | An extra−terrestrial materialized
outside the
rabbit hole today. Calling itself ALICE, this ET claims to
have come
from a planet
named ... |
| 2001−12−20 10:20:58 | Executives at Robots'R'Us today
announced the
launch of their latest multi−function household assistant, IDA
(I'll Do
Anything), the most sophisticated ... |
+−−−−−−−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−−−−−−−−−−−−−−−

The script "ticker.php" needs to connect to this database and extract the five most recent records from it. This data can then be converted into form−encoded data and picked up by the Flash movie.
Here's the code to accomplish this:

The script "ticker.php" needs to connect to this database and extract the five most recent records from it. This data can then be converted into form−encoded data and picked up by the Flash movie.
Here's the code to accomplish this:

<?
// ticker.php
// open connection to database
$connection = mysql_connect("localhost", "root", "secret") or
die
("Unable to connect!");
mysql_select_db("news") or die ("Unable to select database!");
// formulate and execute query
$query = "SELECT body FROM stories ORDER BY date DESC LIMIT
0,5";
$result = mysql_query($query) or die("Error in query: " .
mysql_error());
if (mysql_num_rows($result) > 0)
{
// iterate through rows
while($row = mysql_fetch_object($result))

{
// build headline string
$str .= $row−>body . " * ";
}
// print output as form−encoded data
echo "content=" . urlencode($str);
}
// close connection
mysql_close($connection);
?>

Again, this is fairly simple. The script first connects to the database server, selects a database and executes an SQL query to select the five most recent stories from the system. A "while" loop is used to iterate over the returned resultset, with the content of each record appended to a single string, separated by an asterisk.

Once the entire string has been constructed, it is encoded via PHP's urlencode() function and sent to the standard output, where it can be picked up by the Flash movie. If PHP isn't your cup of tea, you can also do this in Perl − here's the code you'll need:

#!/usr/bin/perl
# load module
use DBI();
# connect
my $dbh =
DBI−>connect("DBI:mysql:database=news;host=localhost", "root",
"secret", {'RaiseError' => 1});
# execute query
my $sth = $dbh−>prepare("SELECT body FROM stories ORDER BY
date DESC
LIMIT 0,5"); $sth−>execute();
print "content=";
# iterate through resultset
while(my $ref = $sth−>fetchrow_hashref())
{
print "$ref−>{'body'} * ";
}
# clean up
$dbh−>disconnect();

Here's what the output of the script might look like:

content=Executives+at+Robots%27R%27Us+today+announced+the+launch+of+thei
r+la
test+multi−function+household+assistant%2C+IDA+%28I%27ll+Do+Anything%29%
test+multi−function+household+2C+t
he+most+sophisticated+...+%2A+An+extra−terrestrial+materialized+outside+
he+most+sophisticated+the+
rabbit+hole+today.+Calling+itself+ALICE%2C+this+ET+claims+to+have+come+f
rabbit+hole+rom+
a+planet+named+...+%2A+

With the server−side component in place, and the Flash movie all prepped and ready to go, all that's left is to test the movie again. This time, the text box should be dynamically populated with the results of the SQL queries in the script above, and should display this data as a scrolling news ticker along the bottom of the movie.
 

As the database is updated with new stories, the Flash file will automatically read and display them via the server−side script "ticker.php". Pretty cool, huh?

Another, more advanced example involves constructing a Flash menu dynamically, from the information in a database. This allows you to build menus that can grow and shrink automatically, as the information in the database changes, and it's a guaranteed entry into Flash geekdom. The process is fairly complicated, so let me run you through a quick theoretical overview before we get
started. Most of the work here happens via an ActionScript function named duplicateMovieClip(), which makes it possible to programmatically clone a Flash movie clip symbol. So, if you had a single movie clip symbol, representing a single menu item, you could combine the duplicateMovieClip() function with a loop to spawn numerous copies of that single menu item, and thereby build an entire menu dynamically.


This might seem a little far−fetched, but it works pretty well...as you'll see very shortly. First, though, let's get all the pieces together.

Let's assume that the data to be used for the menu is stored in a MySQL database table named "menu", and that it looks like this:

+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+
| link | label |
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+−−+
| http://www.elitesolutions.com/services/ | Services |
| http://www.elitesolutions.com/company/ | Company |
| http://wwwelitesolutions.com/mcenter/ | Media Center |
| http://www.elitesolutions.com/account/ | Your Account |
| http://www.elitesolutions.com/community/ | Community |
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+−−−

Pop open Flash, create a new movie, and create a couple of new symbols. The first one is a graphic symbol containing a single−line dynamic text box − name the symbol "text" and the data variable "label".

At a later stage, I'll be using ActionScript to set a value for this "label" variable.
Next, create a button symbol, one which includes keyframes for up, over and down states.

Here's what mine looks like:

Name this button symbol "circle".
In case you're wondering how I created this, it's fairly simple. In the Symbol Editor, use the Oval tool to create a hollow circle  (remember to make the fill colour transparent to achieve the hollowed−out effect) for the Up state.

Next, insert a new keyframe for the Over state, and place a smaller inner circle within the outer one. Make sure that this one has a fill colour (I've used red).

Finally, create a movie clip symbol named "item".
This symbol is what I'll be using to generate the menu items in my dynamic Flash menu. It should contain both a button (which the user can click to go to a specific URL) and a label (which describes the menu item). You've already created both these components; all you need to do is drag and drop them from the Library into the movie clip Symbol Editor.

Yes, that's right − your movie clip symbol is made up of two other symbols. No, I'm not smoking a controlled substance − all will become clear shortly. Now, right−click the "circle" symbol in this movie clip and insert some ActionScript:

on (release) {
getURL (url);
}

At a later stage, I'll be using ActionScript to set a value for this "url" variable.

At this point, your Library should contain three symbols − "text" (the label), "circle" (the button) and "item" (the container for both).

Drag and drop an instance of the "item" symbol onto the Stage.

Use the Modify −> Instance command to give this instance a name − I called mine "itemInstance". This name will be used to reference the instance when creating copies of it via the duplicateMovieClip() function.

Right−click the first frame (this should be a keyframe), and add some ActionScript to it.

itemInstance._visible = false;
loadVariablesNum ("http://localhost/menu.php", 0);

This will first make the instance invisible, and then load the variables found at the URL "menu.php". Let's look at that script next:

// menu.php
// open connection to database
$connection = mysql_connect("localhost", "root", "secret") or
die
("Unable to connect!");
mysql_select_db("menu") or die ("Unable to select database!");
// formulate and execute query
$query = "SELECT link, label FROM menu";
$result = mysql_query($query) or die("Error in query: " .
mysql_error());
if (mysql_num_rows($result) > 0)
{
// iterate through rows
while($row = mysql_fetch_object($result))
{
// build label string
$labelStr .= $row−>label . "|";
// build link string
$linkStr .= $row−>link . "|";
}
// print output as form−encoded data
echo "items=" . urlencode($labelStr) . ".
urlencode($linkStr);
}
// close connection
mysql_close($connection);
?>

This script does the hard work of connecting to the database, extracting the menu items and their
corresponding links, and creating a URL−encoded string that Flash can use. It's important to note, at this point, the format in which the data is output. All the menu labels are compressed into a single string, separated by a pipe, and assigned to the variable "items", while all the corresponding URLs are similarly concatenated and assigned to the variable "urls". Here's an example of what the output of this script might look like:

items=Services|Company|Media+Center|Your+Account|Community|
%2F%
2Fwww.melonfire.com%2Fservices%2F|http%3A%2F%2Fwww.melonfire.com%2Fcompa
ny%2
F|http%3A%2F%2Fwww.melonfire.com%2Fmcenter%2F|http%3A%2F%2Fwww.melonfire

F|.com
%2Faccount%2F|http%3A%2F%2Fwww.melonfire.com%2Fcommunity%2F|

All that's remaining is to write the ActionScript code that reads these variables, parses them and uses them to create multiple instances of the "item" symbol. Right−click the "item" variable, pop open the Actions panel, and add the following code to it:

onClipEvent(data)
{
// split variables into array
items = items.split("|");
urls = urls.split("|");
// get position of template movie clip
yPos = getProperty("itemInstance", _y);
// iterate over array elements
for (i=0; i {
// clone movie clip and name it
duplicateMovieClip ("itemInstance", "itemInstance"+i, i);
// set position
setProperty ("itemInstance"+i, _y, yPos+i*50);
// set variables
set ("itemInstance"+i+".label", items[i]);
set ("itemInstance"+i+".url", urls[i]);
}
}

The onClipEvent(data) event handler is triggered whenever the Flash movie completes loading the variables imported via loadVariables(). This is necessary because Flash loads variables asynchronously, which means that it doesn't wait for the variables to be fully loaded before proceeding to the next statement of the script. By wrapping the code in an onClipEvent() handler, I'm ensuring that the it's executed only after the variables have finished loading. This doesn't always work as advertised, though − keep reading for a couple of caveats to this technique. Once the variables have been loaded, the split() function is used to break the concatenated label and link strings into their constituent parts

items = items.split("|");
urls = urls.split("|");

and a "for" loop is used to iterate over the resulting arrays. This "for" loop does a number of important things. First, it creates a duplicate of the "itemInstance" movie clip, and gives it a unique name by suffixing the array index to the name.

duplicateMovieClip ("itemInstance", "itemInstance"+i, i);

Next, it sets the vertical position of the newly−created movie clip, via the instance's "_y" property. This position is calculated via a simple algorithm, which allows each additional instance to be placed below the previous one.

setProperty ("itemInstance"+i, _y, yPos+i*50);

Finally, the movie clip's "label" and "url" values are set using the set() function; these values are used within the "text" and "circle" symbols respectively (you remember I mentioned these on the previous page).

set ("itemInstance"+i+".label", items[i]);
set ("itemInstance"+i+".url", urls[i]);

These two lines of code set the newly−created menu item's label and target URL respectively.
All that's left is to test the movie. If all has gone well, this is what you should see: It should be noted at this point that I sometimes encountered problems while using the onClipEvent(data) event. In case you find that your Flash movie isn't loading the variables correctly, you might want to consider
removing the

onClipEvent(data)
{
// code
}

handler from the movie clip instance, and instead add a new keyframe (maybe around frame 3?) containing the following code:

// split variables into array
items = items.split("|");
urls = urls.split("|");

// get position of template movie clip
yPos = getProperty("itemInstance", _y);
// iterate over array elements
for (i=0; i {
// clone movie clip and name it
duplicateMovieClip ("itemInstance", "itemInstance"+i, i);
// set position
setProperty ("itemInstance"+i, _y, yPos+i*50);
// set variables
set ("itemInstance"+i+".label", items[i]);
set ("itemInstance"+i+".url", urls[i]);
}

This forces Flash to run the split−into−array−and−create−duplicate−instances code whenever the movie plays, instead of waiting for the event handler to be triggered. It's a somewhat brute−force solution to the problem the first option is far safer, not to mention also being the one Macromedia recommends  which is why you should only use it if you find yourself in dire straits.

In this article, I introduced you to data−driven Flash applications, demonstrating how you can use a database and a server−side script in combination with the new data retrieval capabilities in Flash 5 to dynamically construct Flash movies. I also showed you a couple of simple examples, including a database−driven Flash news ticker and a dynamically−constructed Flash menu. However, building Flash movies from a database is only the tip of the iceberg. Flash comes with a number of tools that allow you to add new types of interactivity to your movies, including creating forms capable of accepting user input and parsing XML data sources. I'll be discussing these capabilities in detail in upcoming articles − but until then, chew on these links, and I'll see you soon!
 

Macromedia's Flash resource center, at http://www.macromedia.com/software/flash/productinfo/tutorials/
FlashKit, at http://www.flashkit.com/
Virtual−FX, at http://www.virtual−fx.net/
Webmonkey's Flash section, at http://hotwired.lycos.com/webmonkey/multimedia/shockwave_flash/


Building Flash Forms


Before we get started with building a Flash form, you need to know a little theory.


Most HTML forms send the data they collect from the user to a server−side script, which is actually responsible for processing the data. This server−side script, usually written in a language like Perl or PHP, actually takes care of doing something useful with the data − for example, using it to build a database query, writing it to a file, and/or generating a result page.

Flash forms work much like HTML forms, except that the constructs used to build them are a little different. A Flash form can be programmed to connect to a specific server−side script, and to pass form variables to it via either GET or POST methods.

In order to better understand this, let's consider a simple example. Pop open Flash, create a new movie and then create a new Button symbol. Name it "textBox"

In the Symbol Editor, define a rectangular textbox,

and then use the Windows −> Panels −> Text Properties panel to turn it into an input text box. Set a variable
name for this text box as well − I've called mine "name".

This is the form variable which will store the user's input, and which will be passed forward to the server−side script.

Back in the Stage, drag and drop a copy of this symbol into the workspace. Add some descriptive text above it if you like.

Next, it's time to connect the text box with a server−side script. Since I want the server−side script to be invoked when the Flash form is submitted (or, in this case, when the user enters some data into the text box and hits the Enter key), I need to add some ActionScript to the symbol. Right−click the symbol instance, pop up the ActionScript editor and add the following code to it:
 

on (keyPress "<Enter>") {
getURL ("matrix.php", "", "GET");
}


This is fairly self−explanatory, even if you've never programmed in ActionScript before. When the form input box receives an Enter keypress, it will invoke the URL "matrix.php", and submit the form data to that URL via the GET method. It is then up to the server−side script to decide what to do next.

Let's see what "matrix.php" looks like:

<html>
<body>
Welcome to the Matrix, <? echo $_GET['name'];?>
</body>
</html>

Extremely simple, this − all it does is accept the form data from the Flash form, and print a simple Web page with a message incorporating the form data. Note that the script references the data entered by the user into the form input box via its variable name  you'll remember that I defined this variable, "name", a couple steps
back when first creating the symbol.


Export the movie as a Flash SWF file, place it in an appropriate location under your Web server root, and access it via your browser. Here's what you should see:

Enter some data, and hit the Enter key. The Flash form will submit your entered data to the "matrix.php" script, and you'll see something like this:

Welcome to the Matrix, john

Obviously, that was a very primitive example, though one that did demonstrate the concept of integrating user−supplied data with a server−side script via a Flash movie. Now, how about a twist?

This next example uses the data entered into a Flash form to query a database and return a list of matches. In order to create the form, create a new Button symbol, in much the same way as you created the one on the previous page. Name the form variable within the symbol "q", and add a copy of the instance to the Flash movie.

Once that's done, add some ActionScript to the symbol instance, referencing the server−side script "search.php" − this time, use POST to send the form variables to the script.

on (keyPress "<Enter>") {
getURL ("search.php", "", "POST");
}

All that's left now is to write the PHP script "search.php". Here's what mine looks like:

<html>
<head><basefont face="Arial"></head>
<body>
<h2>Search Results</h2>
<ol>
<?
// search.php
// get query term
$query = trim($_POST['q']);
// open connection to database
$connection = mysql_connect("localhost", "user", "pass") or
die ("Unable
to connect!");

mysql_select_db("db20139a") or die ("Unable to select
database!");
// formulate and execute query
$query = "SELECT * FROM data WHERE tag LIKE '%$query%' OR
keyword LIKE
'%$query%'"; $result = mysql_query($query) or die("Error in
query: " .
mysql_error());
// get record
while($row = mysql_fetch_object($result))
{
echo "<li>";
echo "<a href=go.php?id=$row−>id>$row−>tag</a>";
echo "<br>$row−>title";
echo "<p>";
}
// clean up
mysql_close($connection);
?>
</ol>
</body>
</html>

Here's what the search box looks like,

and here's a sample results page.

If you're using the latest version of Flash, Flash MX, you'll be happy to hear that Macromedia's included a bunch of new form controls in it. These controls allow you to build ever more complex forms, including forms containing list boxes, radio buttons and check boxes.
To access these, use the Window −> Components command to pop up a panel containing these new form components.

Let's build a simple form using some of these components. Pop open a new Flash movie, and add a couple of static text boxes to it

Next, add form input fields next to each of these − name the corresponding variables "name" and "species" respectively.

How about checking the species type as well? Drag a couple of radio button instances from the Components panel into your form,

and click on each one to set the properties for it. In the Properties panel that opens up, click the Parameters tab and set the label for each radio button.

The label attached to the radio button instance on the Stage should change simultaneously.

Also set the group name for the radio buttons. Since this is an either−or choice, you should make sure that both radio buttons have the same group name − I've used "speciesType".

Next, how about adding a list box? Drag and drop a copy of the Combo Box symbol from the Components panel into the Stage. Name it "residence"

At this point, the box doesn't have any values in it − but you can fix that by popping open its Properties panel, going to the Parameters section, and filling up the Labels and Data sections. The Labels section contains the items to be displayed within the box, while the Data section contains the corresponding values to be sent to the server−side script.

And here's what the combo box should look like once you're done.

Finally, we need a button to actually submit the form. Pull out a Push Button symbol instance from the Components panel, and add it to your almost−complete form. Alter the label via the Properties panel, so that it says something a little more helpful.

While in the Properties section, add a click event handler to the form. This is an ActionScript function that is invoked whenever the button is clicked.

At the end of all this activity, here's what your form should look like:

Next, we need to write a little ActionScript to submit the form data to a server−side script. Select the first keyframe in the Timeline, pop open the Actions panel, and add the following code to it.

function doSubmit()
{
userData = new LoadVars();
userData.name = name;
userData.species = species;
userData.speciesType = speciesType.getValue();
userData.residence = residence.getValue();
userData.send("register.php", "", "post");

Here's what this all means:
The LoadVars() object is what actually packages the data for transmission to the server−side script...and so, the first task is to create an instance of this object.

userData = new LoadVars();

Once that's done, I've created object properties corresponding to the various form elements, and assigned values to them from the various input fields from the form.

userData.name = name;
userData.species = species;
userData.speciesType = speciesType.getValue();
userData.residence = residence.getValue();

Note my usage of the getValue() methods to acquire the value of the selected items in both the radio button set and the list box. ActionScript also offers the getSelectedItems() function, which can be used to retrieve the selected items in a multiple−select list box (not demonstrated here). Once all the form data has been loaded into the object, the send() method is used to submit this data to a
server−side script − in this case, "register.php".

userData.send("register.php", "", "POST");

Pretty simple − the variables from the form are sent to the script "register.php" via POST. Let's see what that script does.

<?
$name = $_POST['name'];
$species = $_POST['species'];
$speciesType = $_POST['speciesType'];
$residence = $_POST['residence'];
// open connection to database
$connection = mysql_connect("localhost", "user", "pass") or
die ("Unable
to connect!");
mysql_select_db("db20139a") or die ("Unable to select
database!");
// formulate and execute query
$query = "INSERT INTO aliens (alien_name, species_name,
species_type,
residence_type) VALUES ('$name', '$species', '$speciesType',
'$residence')"; $result = mysql_query($query) or die("Error in
query: "
. mysql_error());
// clean up
mysql_close($connection);
?>

This should be familiar to you if you've programmed in PHP before − the data entered by the user into the form is extracted from the special $_POST array and plugged into an SQL query template. A connection to the database server is initiated, this SQL query is then executed, and the user data is inserted into the database.

The example you just saw submitted the user's input to a PHP script, thereby redirecting the browser to a fresh page. In case you'd like this result page to also be generated in Flash, Flash MX includes a new ActionScript function named sendAndLoad(), which allows you to submit form data to a server−side script and read the response back into the Flash movie for further processing. This response can then be used to build a new Flash movie on the fly.


If this seems like alien technology to you, don't be afraid − it's not very difficult to do. First, you need to set up your server−side script so that it returns a set of variable−value pairs as URL−encoded form data − as the following example demonstrates:

alpha=1&beta=45

These variables can then be read into Flash and used to assign values to variables within the Flash movie. Consider the following revision of the ActionScript code above, which demonstrates the process:

function doSubmit()
{
userData = new LoadVars();
userData.name = name;
userData.species = species;
userData.speciesType = speciesType.getValue();
userData.residence =
residence.getValue();
response = new LoadVars();
response.onLoad = getResponse();
userData.sendAndLoad("register.php", response, "post");
}
function getResponse(result)
{
if(result == true)
{
// use result values
}
else
{
// display error
}
}

In this case, a new instance of the LoadVars() object has been created, this one designed to hold the variable package returned by the server−side script. When this response is received by the Flash movie, the onLoad event handler is triggered, and the getResponse() function invoked.

Note the difference in the technique used to actually submit the form data to the server − the previous example used the send() method, which only submitted the data, while this one uses the sendAndLoad() method, which both submits data and accepts a response. The getResponse() function returns an object, whose properties correspond to the variables returned by the server−side script. So, if the server−side script returned the string,

color=red&shape=round

which contains the variables "color" and "red", I could modify the getResponse() function above to use them like this:

function getResponse(result)
{
if(result == true)
{
set("itemInstance.color", result.color);
set("itemInstance.shape", result.shape);
}
else
{
// display error
}
}

In this case, variables within the Flash symbol "itemInstance" are being set to the values returned by the server−side script "register.php", via the set() method.

And that's about it for the moment. In this article, I demonstrated how Flash could be used to build simple Web forms to collect user data on your Web site or within your Flash application. I showed you how to build simple text input boxes, and link them to a form processing script that does something useful with the information submitted. I also gave you a crash course in the new form controls that ship with Flash MX, illustrating how they can be used to build ever more complicated forms, and how they can be combined with new ActionScript functions to both submit form data and process the response to dynamically build a results page.


On a concluding note, it's important to remember that building a form in Flash is a double−edged sword. On the one hand, you get access to all of Flash's cool animation functions, which make it possible to build graphically−rich, user−friendly forms rapidly and efficiently; on the other, the more complicated your forms are, the longer they'll take to download and render. Flash offers creative developers an immense amount of power − it's wise to remember that it should be used carefully.

last updated 09/13/2005


EliteSolutions and  MaxNet IT Solutions Serving Vancouver Island and British Columbia  with  Innovative IT Solutions for Small Business

|IT Solutions| |Web and Internet Solutions | |Tech Articles | |Training| |Other Sites of Interest| |Site Map| | Online Courses | |Home|