Server-Side Flash-Scripts Databases and Dynamic Development-0764535986
Server-Side Flash-Scripts Databases and Dynamic Development-0764535986
Table of Contents
page 1
Server-Side Flash: Scripts, Databases, and Dynamic Development
Copyright © 2001 Hungry Minds, Inc. All rights reserved. No part of this book, including interior design,
cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic,
photocopying, recording, or otherwise) without the prior written permission of the publisher.
ISBN: 0-7645-3598-6
10 9 8 7 6 5 4 3 2 1
1B/SQ/QW/QR/IN
Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United
Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia
Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for
Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by
ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson
Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR
International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS
Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for
Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media
Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de
Panama S.A. for Panama; by American Bookshops for Finland.
For general information on Hungry Minds’ products and services please contact our Customer Care
department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax 317-572-4002.
For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and
foreign-language translations, please contact our Customer Care department at 800-434-3422, fax 317-
572-4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint
Boulevard, Indianapolis, IN 46256.
For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care
department at 212-884-5000.
For information on using Hungry Minds’ products and services in the classroom or for ordering
examination copies, please contact our Educational Sales department at 800-434-2086 or fax 317-572-
4005.
For press review copies, author interviews, or other publicity information, please contact our Public
Relations department at 317-572-3168 or fax 317-572-4168.
For authorization to photocopy items for corporate, personal, or educational use, please contact
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED
THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO
REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR
COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN
THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES
REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS
OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT
page 2
Server-Side Flash: Scripts, Databases, and Dynamic Development
Macromedia Software, Copyright (c) 1998-2000 Macromedia, Inc. 600 Townsend Street, San Francisco,
CA 94103 USA. All Rights Reserved. Macromedia, Fireworks, Dreamweaver, Generator, and Flash are
trademarks or registered trademarks of Macromedia, Inc. in the United States and/or other countries.
Trademarks: Hungry Minds and the Hungry Minds logo are trademarks or registered trademarks of
Hungry Minds, Inc. All other trademarks are property of their respective owners. Hungry Minds, Inc. is
not associated with any product or vendor mentioned in this book.
About the Authors
William B. Sanders has published two previous books on Flash 5 and has been an avid devotee of
Flash since Flash 3. Having written a total of 35 computer books on a range of topics from assembly
language programming to hypertext scripts, Bill’s diverse background helped provide the wide range of
connections with Flash 5 on the server-side found in this book. Bill is a professor in the University of
Hartford’s innovative program in Interactive Information Technology. He lives in a rural setting in
Connecticut with his wife, Delia, and dog, Bogee.
Mark Winstanley is the author and editor of many books focusing on Flash. He is an accomplished
computer programmer and musician who consults for clients such as Virgin Records and Time Warner.
Mark is president and cofounder of MultiMeteor, Inc., which hosts the FlashCore.com worldwide
community, Web site, and developer training, as well as the Los Angeles Macromedia Flash Users
Group. Currently living and working in Los Angeles, he is always achieving new ways of bringing
convergence and technological integration to the forefront of development and sharing his knowledge
with the Web development community at large.
vi
Credits
Acquisitions Editors
Jodi Jensen
Development Editor
Heather Stith
Technical Editors
Heather Stith
Editorial Manager
Colleen Totz
Project Coordinator
Nancee Reeves
Graphics and Production Specialists
Laura Moss
Media Development Specialist
Angela Denny
Media Development Coordinator
page 3
Server-Side Flash: Scripts, Databases, and Dynamic Development
Marisa E. Pearman
Cover Image
Deborah Reincrio
Special Help
page 4
Server-Side Flash: Scripts, Databases, and Dynamic Development
Preface
Flash 5 is well known as a powerful and dynamic front end for the Web. However, Flash is also a great
interface for server-side applications. Unlike forms in HTML that require different code for different
browsers, Flash 5 is stable across browsers. This stability means that viewers of any Flash movie see
the same thing no matter what browser they’re using, and the developer has to write only one version of
a movie.
This book shows you exactly how to work with server-side applications with everything from CGI to
PHP. And it shows you how to create XML documents and read the documents using Flash 5’s new
ActionScript XML objects. You also learn how to create and use Generator objects in Flash. On top of
that, we tried to include all the little undocumented secrets in Flash that even some of the pros don’t
know about, such as using cookies with Flash and printing what you want from Flash.
For some readers, this book may be your first venture into the server-side world of the Internet and the
Web. To make the transition as enriching and pleasing as possible, we provide tutorials for using Active
Server Pages (VBScript), Perl/CGI, PHP, and XML. Likewise, the Structured Query Languages of both
SQL and MySQL are introduced so that you can pull data out of a Microsoft Access or MySQL file. Even
if you know nothing about the server-side world of the Web, you can use this book to create and launch
your own server-side applications that are fully integrated with Flash 5.
To further ease your transition from client-side to server-side scripts, we’ve made arrangements with
hosting services for readers to have free trial access to a real-world server while learning the material.
In this way, you can use any version of Windows or Macintosh OS while your server scripts reside on an
NT or Linux server. So, even if you have never worked with any type of server-side applications, CGI,
PHP, and ASP will be much easier to master because you won’t have to format your system to be both
client and server. The section “Using the Free Trial Hosting Services” at the end of this Preface gives
you more details. In addition, you can find steps for accessing these free services in both the “What’s on
the CD-ROM?”appendix and on the CD bound into the back of the book.
Most of the Flash 5 movies and scripts we use as examples are straightforward and designed to show
you how to connect Flash with a server-side application. The tutorials in Perl, ASP, PHP, and XML are
designed to give you a practical running start in each of these languages, and this book serves as an
introduction to these advanced topics as they relate to Flash. The several little projects in the book are
meant to help you through this transition, and two larger projects in gaming and e-commerce at the end
of the book show how you can use Flash 5 and ActionScript with practical applications.
page 5
Server-Side Flash: Scripts, Databases, and Dynamic Development
Windows
Macromedia recommends the following minimum requirements for running Flash 5 on a Windows
system:
Intel Pentium processor; 133 MHz or equivalent (200 MHz recommended) processor
Windows 95/98, ME, Windows 2000, NT 4.0 or later
32MB of available RAM (64MB recommended)
40MB of available disk space
Color monitor capable of 800 ∞ 600 resolution
CD-ROM drive
Macintosh
Macromedia recommends the following minimum requirements for running Flash 5 on a Macintosh:
Power Macintosh PowerPC (G3 or higher recommended)
MacOS 8.5 or later
32MB of available RAM
40MB of available disk space
Color monitor capable of 800 ∞ 600 resolution
CD-ROM drive
Note These are the minimum requirements. As with all graphics-based design tools,
more capability is definitely better for using Flash 5, especially in terms of
memory and processor speed.
page 6
Server-Side Flash: Scripts, Databases, and Dynamic Development
Flash 5. The chapter explains object manipulation and the most efficient ways to deal with tracking
multiple objects in Flash 5. These concepts are essential to understand — whether you are working with
Flash in general or working with all the pieces that go into a game. Chapter 9 expands on the dynamic
elements discussed in Chapter 8 as it walks you through the development of a more complex game.
Key combinations
When you are instructed to press two or more keys simultaneously, each key in the combination is
separated by a plus sign, as shown in the following example:
Ctrl+Alt+T (Cmd+Option+T)
The first key combination tells you that if you’re working in Windows, you should press the Ctrl, Alt, and
T keys all at the same time. If you’re working on a Mac, you should press the Cmd, Option, and T keys
together. (In pressing the three keys, you can first hold down one or two of the keys and then add the
final key. You don’t have to press all three at exactly the same moment.) Release all the keys at the
same time.
Mouse instructions
When you’re instructed to click an item, move the mouse pointer to the specified item and click the
mouse button once. Windows users use the left mouse button unless otherwise instructed. Double-click
means to click the mouse button twice in rapid succession.
When you’re instructed to select an item, you may click it once as previously described. If you are
selecting text or multiple objects, click the mouse button once, hold it down, and then move the mouse
to a new location. The color of the selected item or items inverts to indicate the selection. To clear the
selection, click once anywhere on the Web page.
Menu commands
When you’re instructed to select a command from a menu, you see the menu and the command
separated by an arrow symbol. For example, when you’re asked to choose the Open command from the
File menu, you see the notation File → Open. Some menus use submenus, in which case you see an
arrow for each submenu: Modify → Transform → Edit Center.
Typographical conventions
We use italic type to indicate new terms and for emphasis. We use boldface type to indicate text that
you need to type directly from the computer keyboard.
page 7
Server-Side Flash: Scripts, Databases, and Dynamic Development
Code
A special typeface indicates ActionScript or other code, as demonstrated in the following example of
PHP code:
for($counter=0;$counter<$cusNum;$counter++) {
$row=mysql_fetch_row($result);
}
This special code font is also used within paragraphs to make elements such as XML tags (</name>)
stand out from the regular text.
Italic type in this special font is used in code syntax definitions to indicate that you must substitute an
actual parameter in place of the italicized word(s):
loadVariablesNum( url , levelnumber);
Icons appear in the text to indicate important or especially helpful items. Here’s a list of the icons and
their functions:
Tip Tips provide you with extra knowledge that separates the novice from the pro.
Note Notes provide additional or critical information and technical data on the current
topic.
Cross- Cross-Reference icons indicate places where you can find more
Reference information on a particular topic.
Caution The Caution icon is your warning of a potential problem or pitfall.
On the CD- The On the CD-ROM icon indicates that the accompanying CD-ROM
ROM contains a related file in the given folder. See the “What’s on the CD-
ROM?” appendix for more information about using the CD.
page 8
Server-Side Flash: Scripts, Databases, and Dynamic Development
If you decide not to transfer any domains to the hosting services but to use them instead as test
environments, be sure to remember the unique information given to you when you sign up. For
example, in most cases in this book when you need to enter a URL to your Web server, you see this in
the sample code:
http://www.yourdomain.com
If you haven’t transferred an actual domain name to your Web-hosting test environment, you won’t be
entering an address that starts with www. Instead, you must type the unique URL provided to you when
you sign up with either JTLNet or HosTek. Here’s an example of a unique URL from JTLNet:
http://thebes.jtlnet.com/~youraccount/pagename.html
When signing up with one of the free Web-hosting services, you might be given an IP address to use
instead of a domain. However, using the IP address works the same way. For example, instead of the
domain name you would enter your IP address such as
http:// 216.15.158.57/pagename.asp
Specific information on how to access your account is provided when you sign up for the hosting
service.
Further Information
You can find more help for specific problems and questions by investigating several Web sites.
Macromedia’s own Flash Web site is a good place to start:
www.flash.com
Further Information
You can find more help for specific problems and questions by investigating several Web sites.
Macromedia’s own Flash Web site is a good place to start:
www.flash.com
page 9
Server-Side Flash: Scripts, Databases, and Dynamic Development
Acknowledgments
We were most fortunate to work with the great people who assisted us in this book in one way or
another. Gayle Pietras and Meredith Searcy at Macromedia provided product information and logistical
support for Generator and the Generator servers. Other technical advice from Macromedia was
supplied by Eric Wittman, Brad Bechtel, Matt Wobensmith, Mike William, and Jeremy Clark. The
technical editing by Joel Lee and Jonathan Danylko was first rate and always helpful. Maria Tepora at
Flashnique.com and Nate Yarrington at Entertainovision.com provided graphics used in some of the
example files. Many of the color combinations relied on Leslie Cabarga’s books The Designer’s Guide
to Color Combinations (North Light Books, 1999) and The Designer’s Guide to Global Color
Combinations (North Light Books, expected November 2001).
We were able to arrange the trial hosting services for our readers because of the assistance of Brian
Anderson at HosTek and Joel Lee at JTLNet. Steve Misovich and Lou Boudreau were part of a PHP
group that was very helpful, and David Demers provided insight into ASP. Chris Maden gave invaluable
help on the right way to use XML. George Brophy and Dave Kelley at the University of Hartford provided
support in setting up an NT Server, and John Gray, Chair of the University of Hartford’s Interactive
Information Technology program, provided much-needed general support. Hungry Minds editors Mike
Roney, Carol Sheehan, Chris Johnson, Jodi Jensen, and Heather Stith kept the book on track during
the editorial process, and Margot Maley Hutchison at Waterside Productions is responsible for the
connections that made the book possible.
Server Integration
Flash 5 is now the tool of choice for dynamic, integrated Web sites. To truly interact with the user and
create a customized, dynamic experience, Flash needs to retrieve dynamic data from a Web server and
be able to decipher, operate on, or return that data for storage or more operations on the Web server. In
this chapter, you’ll learn the basics of data transfer over the Internet between browsers and Web
servers and the unique new ways Flash 5 has introduced to send, receive, and deal with this data.
URL encoding is a process by which lists of multiple variables being sent between servers and browsers
are encoded as a single chunk of continuous data. Individual characters within the data chunk that
might be confusing to the browser or server interpreting them are converted into a new special
character or sequence of special characters.
Browsers and servers like to send and receive data in well-defined pieces and don’t want to have to
decide if the space between some data represents the space between someone’s first and last name,
an error, or the beginning of a new piece of data. Web computers look for reserved characters, such as
page 10
Server-Side Flash: Scripts, Databases, and Dynamic Development
ampersands and percent signs, within the data chunk to clearly designate when a variable begins and
ends and when a variable includes a special character. A variable value that contains such a character
could cause problems for the server if the value is not URL-encoded.
To get a feel for how URL encoding works, suppose you defined these two variables in Flash
ActionScript:
address="7095 Hollywood Blvd";
city="Van Nuys";
This code would need to be translated into URL encoding by Flash before being sent across the
Internet. All the spaces between the words in the string variables would be turned into plus signs (+),
and an ampersand (&) would be used to designate the beginning of a new variable:
address=7095+Hollywood+Blvd&city=Van+Nuys
To understand how URL encoding handles special or reserved characters in variable values, consider
this definition in Flash ActionScript:
authors="Winstanley&Sanders";
If this variable were to be passed across the Internet using URL encoding, it would appear this way:
authors=Winstanley%26Sanders
Remember that in the specific syntax of URL encoding, an ampersand (&) is used to designate the point
where one variable ends and another begins when multiple variables are transmitted. If the ampersand
in the variable’s value as defined in Flash wasn’t translated to its URL-encoded value of %26 before
being sent across the Internet, the Web server receiving the data would think that a new variable named
Sanders was about to be defined.
If you’ve ever visited a Web site and suddenly looked up at the link in your browser’s address line and
noticed that it’s turned into a long, cryptic string of text, you’ve seen URL encoding in action.
page 11
Server-Side Flash: Scripts, Databases, and Dynamic Development
Note Again, the beauty in using Flash is that when Flash has to send data out over the
Internet, it does the URL encoding and combining for you! The reverse applies for
when Flash receives data. If the data contains URL-encoded characters, Flash
recognizes these and transforms them back into the actual characters needed.
Flash also splits up any incoming variable/value pairs denoted by ampersands
into individual variables. Nice job, Macromedia!
Don’t worry about having to write URL encoding in Flash, it will happen by itself. Server scripts, on the
other hand, usually need a little bit of help. As you’ll see in Chapter 2 with CGI and Perl, Perl needs a
few lines of code to decipher those URL-encoded variables before it can operate on them correctly.
Variables also need to be formatted as URL-encoded when returned from a server script, and this
functionality often has to be manually coded into the script.
Now that you’ve seen how the characters within an individual variable are displayed in URL encoding,
take a look at what a chain of URL-encoded variables looks like when strung together:
1. Create a new Flash file.
2. Create a button on the stage or drag one to the stage from the Standard library by
choosing Window → Common Libraries → Buttons.
3. Make sure that the ActionScript window is open and in expert mode. Then select the
button you just created by clicking it once.
4. Add the following code to the button:
5. on (release) {
6. name="mark";
7. title="co-author";
8. getURL ("http://www.flashcore.com/index.htm", "_blank", "GET");
}
9. Preview the movie in your Web browser by pressing F12 and then clicking the button
in the Flash movie.
You should see a new browser window pop up with FlashCore.com in it. You may not see an actual
Web page, but what you want to look at is the URL field in your browser. Take a look at the entire URL;
notice that it’s the same as the example in the previous section:
http://www.flashcore.com/index.htm?name=mark&title=co%2Dauthor
In Flash, you defined the two variables name and title and then issued the getURL statement to
launch the page in a _blank or new window. The last argument in the getURL statement is the word
GET. This word specifies that any variables you just defined are to be sent out of Flash along with the
standard URL and attached to the end of it in a query string. Don’t worry, the mysteries of the query
string will be unveiled shortly, but for now just notice that you didn’t have to do anything out of the
ordinary when defining the variables in the Flash ActionScript to have them sent out in a URL-encoded
format. You simply defined your variables and then issued the getURL statement and specified with
GET that variables were to be sent; Flash took over from there, figuring out all the URL encoding for
you. Try adding some extra variable names and values in the ActionScript after title and preview the
page 12
Server-Side Flash: Scripts, Databases, and Dynamic Development
results again. The URL in the pop-up Web browser will become longer and longer as you add more
variables.
As we’ve mentioned, the URL-encoded format for variables is the standard used across the Internet,
and Macromedia logically chose this format as the required format for any external variables to be
loaded into the Flash environment. In this section, you’ll discover how to format and load variables from
external text files, where to put these variables, and how to check for them to arrive before attempting to
operate on them.
If Flash finds nice sets of variables in a URL-encoded format, it will take note of what they are and
transfer their values back to Flash. If Flash can’t make any sense of what it finds inside, it will just ignore
the entire text file. On the one hand, improper formatting keeps your variables out of Flash, but on the
other hand, Flash proceeds with its business and doesn’t display any loud warning messages. Flash is
forgiving and likes to maintain transparency and fluidity in the user experience.
On the CD- You need to copy the files first_variables.fla and first_variables.txt from the
ROM CD-ROM to your hard drive because you’ll be modifying them quite
extensively. Make sure that you put them both in the same directory. It
may be a good idea at this time to transfer all the files for this chapter to a
page 13
Server-Side Flash: Scripts, Databases, and Dynamic Development
new directory on your hard drive where you’ll have an easy time modifying
them and saving changes.
Copy the files first_variables.fla and first_variables.txt from the CD-ROM to a directory
on your hard drive. Open the file first_variables.fla that is now on your hard drive. You’ll see
one green button and a rather large text field. With the Text Options panel open, click the text field and
notice that it has been assigned to display the value of a variable named output should one ever come
into existence.
Choose File → Publish Preview → Default to preview in your Web browser. Click the green button.
Suddenly the big empty text field is filled with lots of text! Figure 1-1 illustrates what you should see.
This text is all contained within the file first_variables.txt and is loaded into Flash through the
loadVariables statement attached to the green button.
Figure 1-1: Flash has loaded a variable with a very long string of text as its value from an external text file.
While you still have the preview of the Flash movie visible, open the first_variables.txt file from
your hard drive in your text editor to examine how the URL-encoded formatting in the text file is
translated into Flash. Begin by comparing what you see in the text file with what you see in the Flash
movie. The first line of code visible in the text file is
&output=This is the text contained in the variable named ‘output’.
Notice the ampersand and then the variable name output and the equal sign (=) following it in the text
file. These items do not appear in the text field assigned to output that is in the Flash movie or
anywhere in the code of the Flash movie because the output variable is defined in the text file. Flash
looks at the text file and sees output properly defined and assigns everything following it as the value
for output.
Lots of lines of raw text in the text file are separated by spaces, carriage returns, and punctuation, which
is not strictly formatted URL-encoded text. We’re cheating a little here. Thankfully we can, because
Flash is forgiving. The key to formatting your text file variables for loading into Flash is the proper use of
ampersands: Begin and end every variable declaration with an ampersand. The ampersands act like big
brick walls, marking off the area where a variable’s value begins and ends.
page 14
Server-Side Flash: Scripts, Databases, and Dynamic Development
Caution Although the ampersand at the very beginning or end of the entire text file is
not always necessary, you should always include them. When these
ampersands are not included, some browsers have trouble interpreting the
data stream or skip the last variable in a series. Ampersands between multiple
variable declarations are always necessary.
Take a look at the bottom lines of text in the text file. A big comment in there says, “HEY LOOK.” Two
lines before those words appear, however, is an ampersand that acts as the brick wall denoting the end
of the variable output. When Flash reaches that second ampersand, it ignores anything it sees
afterwards until it finds another ampersand and then a variable name with an equal sign.
Although spaces between the ampersand, variable name, and equal sign are not allowed when you
declare your variables in the external text file, you can freely use spaces, most punctuation, carriage
returns, and even equal signs inside your variable values. In situations not relating to Flash (such as a
traditional Web browser query string), this kind of formatting would be unacceptable.
Carriage returns
You may have noticed that the gaps between lines of text in the Flash movie are much larger than the
gaps between lines in the text file. That difference occurs because the text file contains an actual
carriage return instead of the URL-encoded equivalent of %0D. If you want the convenience of typing
blocks of text in a text file just like you would a word processor, you could change the line spacing of the
output text field in Flash by selecting it and using the Text Paragraph palette and the line spacing
parameter.
To get normally spaced carriage returns to appear in Flash without changing the text field formatting,
you would type all your lines of text in the external text file in sequence without any carriage returns.
Then, wherever you want Flash to show a new line, you would insert %0D into the text file. The following
example shows how a line from such a text file might look:
&output=Here is line one%0Dhere is line two%0Dhere is line three&
Flash would load this file in and display the following in its output text field:
Here is line one
Here is line two
Here is line three
The carriage returns would display true to form in Flash, but looking at that continuous line of data with
the multiple %0D codes in the text file can get confusing very fast, especially if a dynamic text file system
is being created for a client. By changing the text field formatting on the Flash stage instead of using
%0D in the external text file, you’ll have a text file that is easy to decipher but will, unfortunately, have a
page 15
Server-Side Flash: Scripts, Databases, and Dynamic Development
Flash display with improper spacing between the lines. You’ll have to decide which is more important
when planning your Flash projects.
Formatting multiple variables and values can be slightly more complicated. Flash will automatically
recognize and bring back as many variables and values as you can cram into a text file, but exactly how
you cram those variables in the text file affects the ease with which you can make changes to the file
later.
Imagine if you wanted to create a record for a person’s contact info in a text file. The standard URL-
encoded continuous string format for this information would look something like this:
name=Bob+Jones&address=1840+Grant+St%2E&city=Philadelphia&state=PA&zipcode=19120&age=2
7
This nicely formatted list text file accomplishes the same feat and is much easier to read:
&name=Bob Jones&
&address=1840 Grant St.&
&city=Philadelphia&
&state=PA&
&zipcode=19120&
&age=27&
Notice the beginning and ending ampersands, which denote the breaks between the variables. Writing
the text file in this format makes it easy to see what you’re looking at, and most people can be taught to
recognize and make changes to these types of files. This format is not strict URL encoding, but it works
and is much cleaner to edit than it would be if the variables were in the standard URL-encoded format.
A good general rule might be this: If you ever anticipate modifying multiple variables in an external text
file by hand, use the list formatting method. If you’re using a server scripting language to write your text
files for you (as in Chapter 2), you can use a snapshot of a query string (which is in the standard URL-
encoded format) instead. Flash is happy either way.
Arrays
If you want to put an array in the text file that you want to pull into Flash, you can format the array using
commas to denote the separation between each element in it. For example, if you defined an array in
Flash named carColors and the elements consisted of the colors red, white, blue, and green, you’d
normally define this array in ActionScript with this line of code:
carColors=new Array("red","white","blue","green");
To define this array in an external text file to be loaded into Flash, you would just leave out all the
quotes:
&carColors=red,white,blue,green&
Unfortunately, though, if you loaded this line into Flash, Flash wouldn’t immediately recognize it as an
array; Flash would look at carColors as one single variable with the string literal value of
red,white,blue,green. Flash needs some extra help to get it to recognize carColors as an array.
This extra help comes in the form of the ActionScript command split, which is covered later in this
chapter along with a more detailed explanation of arrays under the heading "Displaying and outputting
arrays."
For now, just keep in mind that if you plan on dealing with a set of data as an array, it should appear in
the text file as one variable name followed by all the values separated by commas (,). Although you can
use any separator you’d like, we recommend sticking with commas because Flash uses this format
when it sends out an array, as covered later in this chapter under the heading “Sending variables to the
server.”
page 16
Server-Side Flash: Scripts, Databases, and Dynamic Development
or
loadVariables ( url, target, method );
Both styles of the loadVariables command call for three parameters: url, target, and method;
method is the only optional parameter.
page 17
Server-Side Flash: Scripts, Databases, and Dynamic Development
Using the self-reference object this saves you the trouble of having to type in a long path to a movie
clip when you’re at the right spot to begin with!
page 18
Server-Side Flash: Scripts, Databases, and Dynamic Development
external text file and format them for use in Flash. The theme of this Web site is that of a jewelry store.
Maria Tepora of www.flashnique.com provided the graphics and artwork for this example.
On the CD- This project uses the jewelrysite.fla file found on the CD-ROM. Open this
ROM file in Flash and then save it to your local hard drive. In that same directory
on your local hard drive, create and save an empty text file named
jewelrydata.txt using your favorite text editor.
The Flash file jewelrysite.fla on the CD-ROM contains some graphics and four buttons on the
right side labeled About Us, Product, Special, and Contact Us. No ActionScripting has been added yet.
The following steps lead you through the process of adding the capability to load in data from a text file
to this Web site:
1. To prepare the text file and fill it with data that you want to load, open the
jewelrydata.txt file you created in your text editor.
2. Add four variables named aboutus, products, specials, and contactus.
Each variable has some text as its value that corresponds to the data you want to
appear when a user clicks one of the four buttons on the right side of the Flash movie.
Enter the following code into your text file:
3. &aboutus=de Legacy Jewelers was founded in 2001 and is a completely
fictitious company for the purpose of displaying the loading of multiple variables&
4.
5. &products=We carry a large assortment of diamond rings, earrings, necklaces,
and fashion jewelry&
6.
7. &specials=This week’s special includes a diamond bracelet for $399.00 and a
gold necklace for $450.00&
8.
9. &contactus=de Legacy Jewelers is open 24 hours a day, 365 days per year and
can be reached anytime at:
1-800-123-4567&
10. Save these changes to the text file jewelrydata.txt and make sure that file is in
the same directory on your hard drive as jewelrysite.fla. (If you encounter any
problems along the course of this example, the text file is also on the CD-ROM.)
11. With the jewelrysite.fla file open in Flash, you must first create a text field
where all the data about the jewelry store is going to be displayed. Use the Text tool
to create a dynamic text field on the stage that fills in the area in the center of the
stage to the left of the buttons. Figure 1-2 shows the approximate placement of this
text field.
page 19
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 1-2: The approximate placement of the dynamic text field on the stage of
jewelrysite.fla.
12. Select this text field, and under the Text Options panel, make sure that Dynamic Text
is selected from the first drop-down menu and Multiline is selected from the second
drop down menu. Check only the Word Wrap check box and make sure the others
are unchecked on the right side of the panel.
13. In the Variable field of the Text Options panel, type in displayfield to associate this
field with the Flash variable displayfield.
14. With the dynamic text field still selected, open the Character panel and choose Times
New Roman in black at a point size of 22. Choose Bold and Italic as well. In the
Paragraph panel, choose Center alignment.
15. Add the following ActionScript to Frame 1 of the ActionScript layer on the main
timeline:
loadVariablesNum ("jewelrydata.txt", 0);
This ActionScript will cause Flash to load in all the variables you defined in the text file the
instant that the movie begins and to make them accessible on the main timeline. Keep in
mind that if you were to upload this to the Web, you’d have to add ActionScript to make up
for the delay in getting the variables, which is covered in this chapter under the heading
“Checking for the arrival of variables.” Because the file involved in this example is on your
local hard drive, there will be no delay, and you can proceed.
16. Add the following ActionScript to the About Us button:
17. on(press){
18. displayfield=aboutus;
}
This code will make the dynamic text field that you created display the text that was loaded in
from the text file jewelrydata.txt for the variable aboutus.
19. Add the same ActionScript to the remaining three buttons, replacing the variable
reference aboutus with the variable names products, specials, and contactus
for the respective buttons.
page 20
Server-Side Flash: Scripts, Databases, and Dynamic Development
20. Test the movie in your browser using F12. As you click each button, you should see
the text that you saved in the file jewelrydata.txt appearing in the dynamic text field.
Figure 1-3 shows the information displayed when you click Contact Us. (If you
encounter any problems, the completed file is available on the CD-ROM as
jewelrysite_completed.fla.)
Figure 1-3: Flash displays one of the variables it loaded from a text file when a user clicks
the appropriate button.
Flash has successfully pulled in a series of variables you defined in an external text file and shown only
the appropriate one in the displayfield text field when each button was clicked. Try opening the text
file and changing the values for the variables and previewing the Flash movie again. You’ll see that
Flash reflects all your changes and pulls in the new updated data. By assigning individual variables to
the dynamic text field, you’ve operated on this data. The next section delves deeper into operating on
external data after you’ve requested it with the loadVariables ActionScript statement.
page 21
Server-Side Flash: Scripts, Databases, and Dynamic Development
need again, so they just store all of them! This storage is great for faster Web surfing because when
your browser encounters a file reference in an HTML page, it first checks the cache storage area
(located on your hard drive) to see whether it has the file handy, instead of downloading it again and
wasting time. Browsers cache just about any file type, including GIFs, JPEGs, HTML pages, SWF files,
and text files.
Caching is bad for dynamic text files that you’d like to load into Flash. Updating your text files doesn’t do
much good if everyone who’s looking at your Flash movie is seeing outdated information. They see
outdated information because their browsers are pulling the text file from their local cache instead of
pulling the new, updated text file from your Web server. The same problem occurs with Flash SWF files
that you’ve made changes to!
Tip Most browsers let you view the area where cached files are temporarily stored. In
Internet Explorer, choose Tools → Internet Options, click the General tab, click the
Settings button, and then click the View Files button. Most browsers also let the
user designate a megabyte limit for storage of files, and they delete the oldest files
stored in memory as new ones are stored. These limitations keep the browser
cache from eating up too much hard drive space; 50MB is usually the average.
A Web browser’s cache references a file only by its name, type, and the Web site it originated from. So
if a file named flashdata.txt has been stored in a user’s browser cache from your Web site, and
that user goes back to your Web page and a Flash movie executes a loadVariables statement that
calls for flashdata.txt, that user is going to get data from the flashdata.txt file stored on his or
her local hard drive instead of the new, updated file from your Web site. This situation has caused many
headaches in the world of Flash.
If these two lines of ActionScript were in the first frame of your Flash movie, and a user came back three
times to visit your site and then looked in his or her browser cache, that user would see something like
the following:
flashdata.txt?reload=456192
flashdata.txt?reload=889056
flashdata.txt?reload=155607
page 22
Server-Side Flash: Scripts, Databases, and Dynamic Development
When you set that random number and then attach it to the filename, you ensure that there’s only a one
in a million chance that a user will not receive the latest and greatest text file information you’ve posted
to your Web site. Of course, this solution also means that users’ browser caches are filled with extra
files every time they visit your site. But most people don’t look in their browser caches, and browser
caches automatically delete excess files anyway, so don’t worry about it. This solution is also the only
way to fix this problem, so feel free to use it often.
Note Even though you specify a variable name in the query string following the text
file’s name, you’re not putting any extra variables into the text file. This code is
merely a trick to fool the browser cache. You can use any variable name you’d
like instead of reload, as well as any range of random numbers. We just thought
"one in a million" looked like good odds!
The same solution works great for loading in SWF files via the loadMovie command. If you’ve
constructed a Flash file that you use as a shell to load in other SWF files that are often changed, you
can use this code:
rn = Math.round(Math.random()*1000000);
loadMovieNum ("contentMovie.swf?reload="+rn, 1);
In this example, the filename contentMovie.swf is the name of the movie you’re loading into Flash.
This trick is indispensable in making sure that anyone viewing your Flash movies always sees the latest
and greatest content provided by you!
If you add these two tags to your HTML code, it will, in some cases, prevent the user’s browser from
caching any files contained in the HTML page. Unfortunately, it doesn’t always work. We’ve presented it
here just so you’re aware of it.
A much better way to hide your content from the end users is to make sure that your Flash SWF files
are difficult, if not impossible, to find in the browser cache. You may wonder what purpose it would
serve for someone to take your Flash movies out of their browser cache and put them on their hard
drive or their own Web site. For one, they could easily put your content on their Web site. By using
loadMovie with some clever masking and timeline control techniques, they can easily make it look like
their Flash movies. In addition, every time you load a text file filled with data into Flash and it appears in
a browser cache, it’s vulnerable to the same interception.
The solution here is deceptively simple and involves nothing more than renaming your Flash movies
and dynamic text files to have extensions other than swf or txt at the end of the filename. You can
choose a typical extension like gif, jpeg, mp3, or even make up extensions like thz and nmb. This
solution works because a movie or a text file loaded into Flash will load correctly as long as the contents
of the file are readable by Flash, regardless of the file extension. For example if you have an SWF
movie named bounce.swf and a dynamic text file named colors.txt, you could rename them to
bounce.gif and colors.jpeg and place them in the same directory as the master Flash movie that
is referencing them via ActionScript. The ActionScript in the master Flash movie would then read:
loadMovieNum ("bounce.gif", 1);
loadVariablesNum ("colors.jpeg", 0);
After executing this ActionScript, the Flash movie now named bounce.gif (originally named
bounce.swf) would be loaded into Level 1. Additionally, the text file colors. jpeg (originally named
colors.txt) containing data that you want to load into Flash would be loaded into Level 0, and the
data would be available on the main timeline. This is a great way to disguise your Flash and dynamic
text files that will appear in the browser cache of someone viewing your Web pages. If a user opens his
or her browser cache after visiting your site, the user wouldn’t see any Flash files or text files, only GIF
and JPEG files. If you have static graphics on your Web pages that have names and extensions similar
page 23
Server-Side Flash: Scripts, Databases, and Dynamic Development
to the disguised files, it’s very difficult for users to distinguish any of the files in their browser cache as
being Flash or Flash-related.
This ActionScript works only when Flash movies or text files are loaded into a Flash movie that already
exists on a Web page (or in a projector file). You can’t rename the original file referenced in the HTML
code in the <OBJECT> and <EMBED> tags to anything other than SWF. This first file must maintain the
swf extension in order for the Flash browser plug-in to load it correctly. The great thing is that this first
Flash file can be completely empty and contain nothing more than a loadMovie action referencing
your disguised files that contain the bulk of the content for your Flash site!
Caution All your ActionScript code is vulnerable to dissection and discovery, even if
you’ve checked Protect From Import in the Flash export dialog box. The
reason your code is vulnerable is because a program called the Action Script
Viewer, available at www.buraks.com, enables a person to vacuum the
ActionScript code out of any Flash movie and use it for their own purposes.
Renaming your files to gif or mp3 extensions can keep the casual viewer from
finding them in their cache and realizing they’re Flash movies. But anyone
who uses a program like Action Script Viewer will see the name of every file
that you’re referencing in your code and follow the trail to eventually find your
movies. For most people, protecting code is more trouble than it’s worth. You
should still, however, be aware of the risks.
Because you’re reading this book, we assume that you’re familiar with the concept of a variable and
how to set one, change one, and even concatenate a few of them together. What many developers
don’t realize is that Flash has some unique ways of dealing with its variables.
Directory assistance
Variables in Flash are stored either in the main timeline of a Flash movie or within an individual movie
clip’s timeline. Timelines are the only places that Flash can set and retrieve a variable. This section
provides some general definitions of the paths that need to precede variables when you want to access
or operate on them in Flash.
When you need to address a submovie clip in an SWF file on another level (from anywhere in Flash),
you use this syntax:
_level4.zoo.cage.tiger.claws=8;
When called from anywhere in Flash, that statement will make the variable named claws, which is
inside the movie clip tiger, which is nested somewhere in an SWF file that has been loaded into
_level4, and has a value of 8.
page 24
Server-Side Flash: Scripts, Databases, and Dynamic Development
The equivalent path in Flash with a series of similarly named movie clips would be as follows:
_root.pictures.vacation.florida
Note For those of you making the transition from Flash 4, the directory tree in Flash
used to use the forward slash (/), but now the JavaScript-like dot syntax has
replaced it.
In the preceding example, florida could be a variable inside the movie clip vacation, or it could be
another movie clip inside of vacation. This example highlights why planning is so important in a Flash
movie. Especially if you’re doing a large, intricate Flash movie, you should plan out all your movie clip
and variable names in advance. Mapping out a flow chart structure with movie clip instance names
along with the names of the important variables they contain is always a good idea. If you need to add
pieces and sections later on, you’ll have a quick reference chart of where to access and/or modify all of
your variables.
Anyone who comes to Flash knowing any other programming language (even BASIC from back in fifth
grade) is fairly familiar with the concept of a global variable. Once a global variable is defined, its value
page 25
Server-Side Flash: Scripts, Databases, and Dynamic Development
is available anywhere just by referencing its name. In addition, if you change the global variable
anywhere in the scripting, its new value will be returned whenever the variable is referenced thereafter.
Macromedia presents the concept of global variables in most of its texts, which would lead most
developers to believe that if on the main timeline you defined the variable petName with a value of
fluffy, that whenever you referenced the variable again anywhere in Flash, you would find that the
petName variable’s value was still fluffy. The reality is completely the opposite due to this fact: All
variables are local to the timelines in which they’re created, but they’re globally accessible. So if you
have eight movie clips on the main timeline, you could have eight variables named petName existing
within those eight movie clips. If you stuck a dynamic text field on the main timeline and assigned it to
reference the variable petName, it would remain empty until some ActionScript on the main timeline
(whether in a frame or a button) defined petName within the scope of the main timeline or until you
changed the reference on the text field to reflect one of the movie clips. Including the scope of the
variable in a text field variable reference is an often-overlooked way to avoid creating additional
ActionScripts. In the following example, we’ll look at how Flash’s variables are all local to the timelines
in which they’ve been defined.
On the CD- In the following example, you’ll need to open the file globalvariables.fla on
ROM the CD-ROM and save it somewhere on your local hard drive.
Upon opening the file globalvariables.fla from the CD-ROM, you’ll immediately notice eight little
houses placed on the stage. Each one of these houses represents an instance of the house movie clip.
These instances are all named house1 through house8 sequentially. Click on any of these instances
with your ActionScript panel open and you’ll notice an onClipEvent statement like the following:
onClipEvent(load){
this.petName="Fluffy";
}
These statements set a unique petName variable for each of the eight instances using the object this
to designate that each instance should set this variable within itself. A text field in each movie clip is
assigned the variable reference petName, so if you preview this movie choosing Control → Test Movie,
you’ll see that each house displays the name of its household pet. (If you’d like to customize this movie
to use your pets’ names, feel free to modify the onClipEvent statements at will.)
To understand how to gain access to these locally defined, but globally accessible variables inside each
instance of the house movie clip, add a text field:
1.Select the first keyframe in the Text Field layer and use the Text tool in Flash to
create a dynamic text field anywhere at the bottom of the stage.
2.With the text field selected, use the Text Options panel to designate it as a Dynamic
Text field, Single Line, with Border/BG checked and HTML unchecked.
3.In the Variable Reference box in the Text Options panel, type in the variable name
petName.
4.Preview the movie and notice that nothing appears in the text field. That is because
the text field is on the main timeline and you have not defined petName anywhere
on the main timeline. The only place it is defined is in each of the house movie
clips.
5.Return to Flash and add a frame action to Frame 1 of the Text Field layer:
petName="FishyWishy";
6.Preview the Flash movie again and you’ll see that your text field reflects the great pet
name FishyWishy because it was defined on the main timeline. The text field,
having no reference before the variable name petName, looks to the timeline in
which it sits as the default for where to retrieve a value for petName and finds
FishyWishy because you defined it in Frame 1.
7.Return to Flash, and with the text field you created selected, change the variable
reference in the Text Options panel to _root.house3.petName and preview the
movie again.
Your text field now contains the petName variable defined in the third house in from the left, which
should be Candy. You’ve suddenly created a ‘window’ to the variable in the timeline of that one movie
clip instance. Try changing the number at the end of the _root.house3.petName reference to 4, 5, or
8 and preview again. By including a reference right in the dynamic text field, you’ve eliminated the need
to add additional ActionScript to get variable values from other timelines displayed on the main timeline.
Defining the variable reference in the Text Options panel effectively opens a pipeline to whatever
timeline, movie clip, or level you desire. Pipelines tend to flow in both directions, so changing the text in
the text field changes the variable in the movie clip instance that the text field refers to. To see this
process in action, follow these steps:
page 26
Server-Side Flash: Scripts, Databases, and Dynamic Development
1.With your dynamic text field selected, change its setting in the Text Options drop-
down menu to Input Text. Make sure that the Border/BG box is checked as well.
2.Make sure to change the variable reference so that it associates this text field with
one of the house movie clips, such as _root.house3.petName.
3.Preview the movie and notice that a value is initially present in your text field identical
to that of the house you chose to specify. Start typing (or deleting) text in your text
field and notice that the text field in the house you’ve referenced changes right
along with it! Figure 1-4 shows how the screen looks when some text is deleted
from the text field referencing the third house.
Figure 1-4: You can manipulate a variable that has been defined in any timeline as long as
you know its path and attach that path to ActionScript code or, in this case, a dynamic input
text field.
The most important point to take away from this example is that although the text field you’re using to
manipulate the variable is on the main timeline, the actual variable is stored on the timeline of the
house movie clip you referenced. The variable is local to that movie clip, but it is globally accessible
with another text field or piece of ActionScript code, as long as you know the path to the variable. Even
though in this example you added a path starting with _root to the variable reference in the text field,
you could just as easily have added a path starting with another level number such as _level5 or even
a reference beginning with _parent. All you’ve done is create another window to a particular variable.
When you select Input Text on the Text Options panel, you have the added ability to reach through that
window and make changes. Using a simple dynamic text field in this way makes it very easy to open up
editable pipelines across timelines and levels.
Tip A good way to store variables so that they stay organized if you really need the
effect of a true global variable is to create a movie clip with no graphics and stick it
somewhere on the main timeline. Give it an instance name of allVariables
perhaps. Then anytime you’re loading variables into Flash you could use the
loadVariables statement and enter a target of _root.allVariables. Any
variables loaded in from an external file would end up in this movie clip that would
act as a kind of depot for all your variables. Then even if you had to display them in
some fancy manner in some remote movie clip that was buried in your Flash
movie, the ActionScript or text field present there would only have to reference
page 27
Server-Side Flash: Scripts, Databases, and Dynamic Development
The addition of array-handling capability to Flash 5 was a welcome addition for just about every Web
programmer. Flash has powerful array-processing features, and you’ll find yourself storing variables in
them time and time again.
Arrays in action
An array is basically an associative list of variable definitions. Instead of a unique variable name for
each value, an array value is referenced by the name of the entire array followed by the value’s position
in the array list. To review the necessary syntax, read the following quick example of an array in action.
These steps describe how to create a list of items and then output their names one at a time into a text
field:
1.Open a new Flash file.
2.Create a dynamic text field anywhere on the stage in Frame 1 and give it the variable
reference output.
3.Select Frame 1 and attach the following ActionScript to it:
page 28
Server-Side Flash: Scripts, Databases, and Dynamic Development
4. itemList=new Array("tomato","grapefruit",2346,"blue");
count=0;
Notice that string values in Flash arrays are enclosed in quotations (“”); numerical values do
not need quotations.
5.Create a button anywhere on stage in Frame 1 and attach the following ActionScript
to it:
6. on(press){
7. output=itemList[count];
8. count+=1;
}
Preview the movie in Flash and click the button. Each time you click the button, Flash displays the next
element in the array itemList. It does this in the button by incrementing count and then appending it
to the end of the array name inside brackets. Brackets tell Flash to evaluate whatever value is inside
them. In this case, Flash is evaluating which value in the array to send back. When you reach the last
element in the array, you won’t see anything in the output field because the variable count has been
incremented past the number of elements in itemList.
Note Change the output line in the button to the following:
output=itemList[3];
Preview the movie again and notice Flash displays the fourth element in the
array, blue, and not the third element even though you’ve specified 3. The reason
is because computers start counting with the number 0 and not with the number 1
like we do. Remember that the first element in an array is referenced by the
number 0 and you’ll always be able to reference the correct value.
This example joins all the elements of an array into a vertical display list:
1.Open a new Flash file.
2.Create a large, multiline dynamic text field anywhere on the stage in Frame 1 and
give it the variable reference output. Make sure it can support at least four lines of
text and do not check the Word wrap box.
3.Select Frame 1 and attach the following ActionScript to it as a frame action:
itemList=new Array("tomato","grapefruit",2346,"blue");
4.Create a button anywhere on stage in Frame 1 and attach the following ActionScript
to it:
5. on(press){
6. output=itemList.join(newline);
}
Preview your movie by choosing Control → Test Movie and then clicking the button. You’ll see that all
the elements have been pulled from the array itemList and displayed in the text field with a new line
between each one.
The basic syntax for join is as follows:
arrayName.join(separator);
Replace arrayName with the name of your array and separator with whatever character you’d like
Flash to stick in between the elements. In the example, we used the reserved ActionScript newline to
put a line between each element, but you can put just about any character in between the elements. If
you use a character, the output will be in one long string rather than on neatly formatted new lines and
you’ll also have to include that character in quotations (""). Try replacing the output line in the button
code in this example with any of the following lines and note the results:
output=itemList.join("!!");
or
output=itemList.join("@");
page 29
Server-Side Flash: Scripts, Databases, and Dynamic Development
or
output=itemList.join(chr(32));
Flash will put all the elements together in a row separated by whatever character you chose. The last
sample code line using chr(32) joins the array elements together using a standard spacebar press,
represented by the character code 32 with an output that looks like:
tomato grapefruit 2346 blue
Caution The Flash 5 release introduced the use of the backslash (\) to designate
certain escaped characters inside of strings you define. The escape character
\r is used to denote a carriage return anywhere where one is needed.
Although this character accomplishes the same purpose as newline, Flash
recognizes it as a completely separate character. You can use either one to
accomplish the task of creating a line break; they just can’t be used
interchangeably.
Follow these steps to load an array into Flash from a text file (where it looks like a string) and convert it
into an actual array inside of Flash:
1.Create a text file in your favorite text editor and save it in a directory on your hard
drive as arraysplit.txt.
2.Inside this text file, put the following line of code and then save your changes:
&carColors=red,white,blue,green&
3.Create a new Flash file and save it as arraysplit.fla inside the same directory as
arraysplit.txt.
4.Create a single-line dynamic text field anywhere on the stage in Frame 1 and give it
the variable reference carColors. Use static text to place the label "carColors -
StringVariable" next to it.
5.Create a single-line dynamic text field anywhere on the stage in Frame 1 and give it
the variable reference carColorsArr. This will be the name of the new array you
create to hold the split variable from the text file string variable carColors. Place the
label "carColorsArr - Array" next to the text field.
6.Create a large multiline dynamic text field anywhere on the stage in Frame 1 and give
it the variable reference output. Make sure it can support at least four lines of text,
and do not check the Word wrap box. Use static text to place the label "Output"
next to it. Figure 1-5 shows the approximate layout of the stage.
page 30
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 1-5: The layout of the stage for the file arraysplit.fla.
7.Select the keyframe in Frame 1 and attach the following frame ActionScript:
8. loadVariablesNum ("arraysplit.txt", 0);
count=0;
This script loads in the variable carColors from arraysplit.txt and makes it available
on the main timeline.
9.Create a button anywhere on the stage and use static text to label it “Split.” Attach
this ActionScript to the button:
10. on(press){
11. carColorsArr=carColors.split(",");
}
This code creates an array with the name carColorsArr that contains the four values from
the string variable carColors loaded in from the text file after Flash splits them apart. Flash
removes the commas and places the four separate values into the array carColorArr.
12. Create a button anywhere on the stage and use static text to label it “Display.”
Attach the following ActionScript to the button:
13. on(press){
14. output=carColorsArr[count];
15. count+=1;
}
16. Preview the movie in Flash by choosing Control → Test Movie. After Flash loads
the variable carColors from the text file, you’ll see it appear in the text field
referencing carColors.
17. Click the Split button that you created. Flash has now created a true array named
carColorsArr from the broken apart values of the string carColors. You’ll see the
whole array appear in the text field referencing carColorsArr, but notice that it looks
exactly the same as the string variable carColors! Behind the scenes, the string
variable carColors you have loaded in from the text file is still just a string variable,
page 31
Server-Side Flash: Scripts, Databases, and Dynamic Development
but the array carColorsArr that you created by clicking the Split button is a true
array. So even though the two text fields are displaying what looks like two strings,
rest assured they are not!
Note When you just reference the array name in a dynamic text field, Flash automatically
puts all the element values together for you to see. It’s kind of like an automatic join
being performed for your convenience.
18. Click the Display button you created. Flash steps through the elements inside the
array one at a time, starting with the 0 element and incrementing the count each
time. Now you see that even though the display of carColorsArr looks the same as
carColors, it is actually an array created by using split You can prove this as well by
changing the button code to reference carColors[count] and observing that it
doesn’t work, because carColors from the text file looks like a string to Flash and
not an array.
19. You can now easily pull individual values from the array you created by just
referencing them using their element numbers. You could also do a join on the
array elements to place them into a list. Change the button code on the Display
button to the following:
20. on(press){
21. output=carColorsArr.join(newline);
}
You’ll now see all the elements in the array joined together, one per line, in the Output field. Again, if
you try to just reference the variable carColors, it won’t work because that variable is just a plain old
string variable to Flash. The text field labeled "carColorsArr - Array" is there to not only show you that
Flash has performed an action when you clicked the Split button, but also to show you how Flash
delivers an array as a whole when asked to just display the whole thing at once. This capability is
important because Flash lists the elements all in a row by separating them with commas. This format is
exactly how Flash sends an array to the server, as you see in the section "Sending variables to the
server."
Although Flash 5 contains a simpler and more effective way to check for variables, this standard frame
loop is still worth exploring because it paints a clearer picture of exactly what is happening when Flash
is waiting for variables. The following example takes you through the process of building a simple frame
loop to check for the existence of variables:
On the CD- The following example utilizes the files frameloop.fla and frameloopdata.
ROM txt found on the CD-ROM. Copy these files into the same directory on your
hard drive and save them.
Start by opening the file frameloopdata.txt in your text editor. Notice that three variables are
defined inside: name, occupation, and flag. The contents of the text file should look like:
&name=Bob&
&occupation=programmer&
page 32
Server-Side Flash: Scripts, Databases, and Dynamic Development
&flag=1&
The first two variables represent whatever data may be in any text file you normally load into Flash. The
third variable flag is designed to be a signal to Flash that the end of all the data has been reached.
You will set the value of this variable to 0 initially in the Flash movie. Then you’ll keep checking to see if
it equals 1. The only way it could eventually equal 1 is if Flash has read in all the other variables in the
text file frameloopdata.txt to reach the very last variable named flag and load that in as well.
Note You don’t have to use the variable name flag when creating your own text files,
but you should decide on a standard variable name that you’ll use at the end of all
your text files and remember to always check for that variable name in Flash.
Other common end-of-data designators are variable names such as endvar or
finished. You can also choose any value for them as well, such as true or yes.
Remember to check for this value in Flash as well.
1.Open the file frameloop.fla in the Flash authoring environment. Notice the three
keyframes at the beginning of the timeline in the Actions layer. In the Text layer,
Frame 1 and Frame 15 each have one keyframe.
2.Reset the flag variable to 0 and load the text file by selecting Frame 1 in the Actions
layer and adding this ActionScript:
3. flag=0;
loadVariablesNum ("frameloopdata.txt", 0);
4.To check to see whether the flag variable has arrived and, if it has arrived, send the
timeline to a place that will operate on any variables loaded, select Frame 2 in the
Actions layer and add this ActionScript:
5. if(flag==1){
6. gotoAndStop("loadcomplete");
}
7.If the flag variable does not equal 1, Flash will continue to play on to Frame 3 where
you’ll send it back to Frame 2 to check again. To set up this process, select Frame
3 in the Actions layer and add this ActionScript:
gotoAndPlay(2);
8.Select Frame 15 in the Text layer and give it a label of loadcomplete by using the
Frame panel.
9.With the playhead still at Frame 15, use the Text tool to put some words on the stage
like “Load Process Complete.” The example here uses 24-point bold Times New
Roman.
10. Create two dynamic text fields below these words at Frame 15. Give one text field
the variable reference name and the other text field the variable reference
occupation. Select the Border/BG text box as well. Figure 1-6 shows the stage
layout.
11. Return to Frame 1 in the Text layer and add some static text with the words
“Loading Please Wait[el].” This text sends the user a message to wait while the
variables are loading. The completed file is available on the CD-ROM as
flashloop_completed.fla if you have any problems.
Preview the movie in Flash by choosing Control → Test Movie. Suddenly you’re transported to Frame
15 where you’ll see that the text fields already contain the two variables that Flash loaded in from the
text file. What happened to the loop and the words “Loading Please Wait”?! What happened is that all
the files are on your hard drive, so Flash got the variables from the text file the instant the
loadVariables statement asked for them. It never got to play through the loop a few times.
Caution The danger in testing Flash files that contain a dynamic text file from your
local drive is that you can never get a sense of whether your failsafe
mechanisms are working. Always upload these files to the Web to check how
these files work under realistic conditions.
page 33
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 1-6: The stage layout for Frame 15 of the frameloop.fla file where the playhead is sent after Flash
has received all the variables.
To remedy this situation, save the file frameloop.fla that you just created and then publish it as
SWF and HTML files. Upload the HTML and SWF files to your Web server along with the file
frameloopdata.txt. Make sure they’re both in the same directory! Now open your browser and type
in the URL to the HTML file you just uploaded. You should now see your loading script in action! If your
Internet connection and server are really fast or there’s no Internet traffic, you may miss it again. Keep
hitting Refresh and sooner or later you’ll get some lag and have to wait for the variables to arrive.
Keep in mind that you can substitute the gotoAndPlay action in the if statement in this example for
any action you’d like to occur when your variables arrive. Also, although this example is built on the
main timeline, you could easily put all these frames into a movie clip and load the variables from there.
Just remember to load them into the movie clip using this as the target in the loadVariables
statement, or if you still wanted to load the variables into _level0, you could change the if statement
to read something like if(_root.flag==1).
page 34
Server-Side Flash: Scripts, Databases, and Dynamic Development
The onClipEvent(load) contains statements after it that will be executed only when the movie clip
that they’re sitting on shows up on the stage. Don’t get this confused with loading variables or loading
anything externally! All this statement means is that whenever that movie clip shows up on the stage,
the statements in the onClipEvent(load) statement are executed. Think of the statement as
onClipEvent(exists) and you’ll be less confused.
The onClipEvent(data) statement works the same way except you need to wait for external
variables in this one. This statement basically says that every time variables from an external text file
show up in the movie clip that this statement’s attached to, the statement will execute the statements
that follow it. You don’t need to set any flags in your text files anymore because Flash is smarter now
and knows when all the data from a text file has been loaded.
Once onClipEvent(data) is attached to a movie clip and that movie clip is listed as the target in a
loadVariables statement (from anywhere in Flash), the onClipEvent(data) statement will
perform its duties once all the data has shown up. This statement is always waiting in background ready
to see if the data has completely arrived. To see how this statement works, follow these steps:
1.On the CD-ROM, open the file clipeventdata.txt and save it to your local hard
drive. This simple file contains two variable definitions:
2. &name=Bob&
&occupation=programmer&
3.Open a new Flash file and save it as clipevent.fla in the same directory that you
saved clipeventdata.txt into.
4.In Frame 1, add some static text with the words “Loading Please Wait [el].” to give the
user a message to wait while the variables are loading. Select this static text and
then press F8 to turn it into a movie clip with a symbol name of “Load Check Clip.”
5.Double-click the movie clip to get inside it and add a stop() action to Frame 1.
6.Create a keyframe inside “Load Check Clip” at Frame 15 by pressing F7 and give it
the frame label loadcomplete.
7.Still at Frame 15 inside the movie clip symbol “Load Check Clip,” create a static text
field on the stage with the words “Load Process Complete.”
8.Below that static text, create two dynamic text fields. Give one text field the variable
reference name and the other text field the variable reference occupation. Select
the Border/BG text box as well. These fields reference the two variables that will be
loaded in from the text file clipeventdata.txt. Figure 1-7 shows what Frame 15
inside "Load Check Clip" should look like.
page 35
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 1-7: The layout of the timeline and stage on Frame 15 of the movie clip symbol
“Load Check Clip.”
9.Return to the main timeline and give the instance of “Load Check Clip” that you just
edited an instance name of loadChecker using the Frame panel.
10. With loadChecker still selected, make sure the ActionScript panel is open and add
the following ActionScript to the outside of it:
11. onClipEvent(load){
12. loadVariables ("clipeventdata.txt", this);
13. }
14. onClipEvent(data){
15. _root.gotoAndStop("loadcomplete");
}
This code accomplishes two things. First, as soon as the loadChecker movie clip loads (exists) on the
timeline (which is right away because it’s in Frame 1), it will load the variables from the file
clipeventdata.txt into itself because it uses the self-reference path this as the target of the
variables. Second, the onClipEvent(data) statement patiently waits until the data has fully arrived
and then sends its timeline to stop at the frame labeled loadcomplete, which is Frame 15. Test the
movie and see what happens. The completed file is available on the CD-ROM as clipevent.fla if
you encounter any problems.
You should see the movie clip jump right to Frame 15 because you’re testing it on your local hard drive.
Upload the HTML, SWF, and TXT files to your Web server to get a better idea of the effects of the delay
while loading the text file. A good way to make a longer lag is to go into the text file and make the
variable occupation a very long paragraph of text, which will lengthen the load time for the file.
As you see, the movie clip instance loadChecker first loads the variables into itself and then waits
until they arrive to perform an action. In this example, it’s only sending its own timeline to a different
frame where it displays the variables. In many dynamic applications, you’re waiting for numerical data in
order to operate on it later. Whatever the case, your data need to arrive in Flash before you can start
adding up numbers or comparing user names and passwords to a list that you have in a text file.
page 36
Server-Side Flash: Scripts, Databases, and Dynamic Development
_root.gotoAndStop("loadcomplete");
}
The applications for using onClipEvent(data) are endless and include password checking,
personalization of a Flash site, and checking to see if someone got the new high score in a game; the
list goes on and on. Just remember that it does no good to use the if statement to start comparing
variables that haven’t arrived in Flash yet, so onClipEvent(data) is your new best friend!
page 37
Server-Side Flash: Scripts, Databases, and Dynamic Development
A browser window should pop up (no Web page will display, though) with the URL specified and a query
string filled with all kinds of excess junk! Then again as they say, “One man’s trash is another man’s
treasure,” although if you’re not aware that every function and object on a timeline is going to be blasted
out to the server, you’re probably going to be leaning towards the “trash” opinion. Anyhow, the complete
URL you see in the browser should look like the following:
http://www.flashcore.com/defaultfile.html
?someFunc=%5Btype+Function%5D&checkMeOut=%5Bobject+Object%5D
&name1=mark&name2=bill
Besides the usual variables, objects, and functions that Flash takes from a timeline and converts to URL
encoding in order to send them to a server, Flash sends any arrays as well. It does this in a fairly simple
manner by automatically taking an array and joining its elements into a single string variable with the
same name as the array and the values separated by commas. If you defined an array in Flash with this
line
carColors=new Array("red","white","blue","green");
and then went on to execute a loadVariables statement to send the array to the server, Flash would
send the entire array out in the form of a string like the following:
carColors=red,white,blue,green
This string does not in any way affect the array itself inside Flash. Flash just combines the elements on
the way out to the server. Another important fact to note is that commas need to be URL-encoded as
their value %2C; Flash does this encoding automatically. So the actual data Flash sends to the server
when sending an array would look like the following:
carColors=red%2Cwhite%2Cblue%2Cgreen
This format is extremely important! On the server side, as you get into the server languages later in this
book, you’ll need to use that language’s version of the split command if you want to operate on the
array elements individually by first converting the URL-encoded %2C back into commas, and then
creating a new array by splitting the string at each comma. What’s interesting is that if your goal is to
just store that array in a text file or database on the server to later send back to Flash, you can just
page 38
Server-Side Flash: Scripts, Databases, and Dynamic Development
leave the string alone. This works because when the server eventually takes what looks like a string and
sends it back to Flash, you can use Flash’s ActionScript split to transform the string back into an
array!
This example uses getURL to show how Flash uses URL encoding on an array and sends it to the
server:
1. Create a new Flash file.
2. Create a button on the stage or drag one in by choosing Window → Common
Libraries → Buttons.
3. Attach the following ActionScript to the button:
4. on (press) {
5. authors="Mark and Bill";
6. carColors = new Array("red", "white", "blue", "green");
7. getURL ("http://www.flashcore.com/nofile.html", "_blank", "GET");
}
8. Preview the movie in your browser and click the button.
You’ll immediately see a window pop-up to a page that doesn’t exist on FlashCore.com. What we’re
looking for here is to see the query string at the end of the URL for a visual representation of how Flash
sends regular variables along with an array. The URL you see in your browser window should have this
query string:
?authors=Mark+and+Bill&carColors=red%2Cwhite%2Cblue%2Cgreen
Whenever you use getUrl or a loadVariables statement, Flash sends any arrays to the server in
the format of a string, with their elements combined and separated by commas that are URL-encoded
as %2C. Just be sure to account for this formatting on the server scripting side to make sure you can
break up the data the way you want.
Flash 5 introduced the capability to pull HTML code directly into Flash and place it into a text field
complete with the correct link and text colors specified in your HTML code. Unfortunately, you can’t just
point Flash to the URL of a Web page and tell it to “go fetch.” Many HTML tags confuse Flash, and you
can load in only very basic HTML.
The way to designate a dynamic text field to parse HTML code in Flash is to check the HTML check box
in the Text Options panel for your text field. A check in this box tells Flash to hunt for and parse any
HTML code it finds inside the variable you’ve associated with the text field. That’s right, you must have a
string variable that contains all your HTML code.
Use these basic guidelines concerning Flash and HTML to help you use this feature successfully:
Begin and end the code with the proper <html> and </html> tags, although this isn’t
completely necessary.
Never include the <head> section; it confuses Flash, and it will display the page title and
anything else right in the text field.
Do not include any body attributes. Flash doesn’t recognize code concerning
background colors or default text colors and link colors. You’ll have to specify them one
at a time.
Do not include any references to tables or other HTML layout items; Flash doesn’t care.
Yes folks, we’re talking about bare bones HTML code here, circa 1993.
Do not include any JavaScript or VBScript.
Flash will parse any text and link colors, but you have to specify them directly for each
block of text or link.
Flash will make any links clickable inside the text field as long you have a properly
formatted <a href> tag in the HTML code.
Any <p> paragraph breaks are overly exaggerated; use line break <br> tags instead.
page 39
Server-Side Flash: Scripts, Databases, and Dynamic Development
Carriage returns in the text file containing the HTML code create line breaks in Flash.
For this reason, you should usually have a server generate your HTML code for Flash
and put it all on one continuous line.
You must precede the opening <html> tag with the name of the variable you want to
associate it with if you’re loading your HTML code in from an external text file.
To see how Flash handles HTML, view the htmlcode.txt text file (it’s on the CD-ROM) in your text editor.
Notice that it contains no <head> section and that even though the body background is set to black
#000000, Flash is going to ignore that setting. The most important part of the htmlcode.txt file is the
variable reference mycode as the very first item followed by an equals sign and then all the HTML code.
This reference basically defines all the HTML code as belonging to a variable named mycode:
mycode=<html>
On the CD- The files htmlcode.fla and htmlcode.txt are on the CD-ROM. Copy
ROM these files to your local hard drive and then open them to view their
contents.
View the file htmlcode.fla in Flash and you’ll notice a button with code to load in the data from the
htmlcode.txt text file. You’ll also notice the dynamic text field with the variable reference mycode and the
HTML check box selected in the Text Options panel.
When you preview the movie in Flash or in your browser and click the button, you’ll see the words Two
Website Links: followed by links to the Web sites of Bill Sanders and Mark Winstanley. The links are
fully clickable right inside the text field in Flash. Unfortunately, Flash doesn’t underline them for you; so
if you want to make your links more visible, color them a different color than any surrounding text. You’ll
have to do this for each link because Flash doesn’t parse the HTML body attributes.
The raw line breaks in the text file create a lot of white space in text fields. If you’d like to go into the
htmlcode.txt text file and delete every carriage return so that all the HTML code sits on one continuous
line of text, you’ll see all the three lines of text display one after the other in the dynamic text field with
no extra white space. By dynamically generating your HTML code using a server script, you can force
all the tags to sit on one line.
You can name the text file with any extension you’d like, such as html or txt, because Flash just looks
inside whatever file you reference for properly formatted HTML code. You can embed links in regular
variables by just including the <a href> and font color tags. If you have long pieces of text, you can
embed links right inside the text fields for the convenience of the user. Just make sure the text field is
set up to parse HTML by checking the appropriate box in the Text Options panel.
For example, if you open the additional CD-ROM file htmlcode2.txt, you’ll see the variable mycode with
some text and then all the tags for the links in between. Try changing the button code in the Flash file
htmlcode.fla to point to htmlcode2.txt and then preview the Flash movie. You’ll see how you can include
HTML code in any variable as long as the dynamic text field is configured to receive it. If the box for
HTML in the Text Options panel for the text field referencing mycode is not checked, you then see all
the HTML tags and code present in the text field when you preview the Flash movie.
page 40
Server-Side Flash: Scripts, Databases, and Dynamic Development
4. Create a new blank keyframe at Frame 10 in the same layer. Place a static text field
here with the words “It Worked!!”
5. Open your favorite text editor and create a file named externalaction.as and save it in
the same directory as your Flash movie include.fla.
6. Inside externalaction.as, place the following line of ActionScript and then save your
changes:
gotoAndStop(10);
7. Preview the movie in Flash or in your browser and you’ll see that the Flash playhead
has jumped to Frame 10 and is displaying your text “It Worked!!”
Please note that what you put in your AS file has nothing to do with URL encoding. It is regular, straight-
up ActionScript! In some instances, you may want to load in variables that you’ve defined like this
because it’s easier to denote their names and values in Flash ActionScript than it is with lots of URL
encoding.
One drawback is that the #include command is not backwards compatible with any other version of the
Flash Player. Another drawback is that if you constantly use this method you don’t get as much
experience using the Internet standard of URL encoding to operate on variables. Then again, URL
encoding is only good for dealing with variable names and values, but external ActionScript files can
contain any ActionScript you’d like!
Caution The files pulled into Flash using #include seem to behave differently than
regular text files that you would load using loadVariables. If you put all the
files on your Web server and then view them through a browser, the external
ActionScript files don’t always appear in the browser cache. Even after you
make changes to the external script and upload them to the Web server, Flash
often seems to still acquire the old file data somewhere. If you’re looking for
consistent dynamic interactivity, use standard text files with the dynamic query
string method described in this chapter or use server-side scripting as
described in later chapters.
By using either JavaScript or direct HTML, you can pass variables into Flash directly from an HTML
page where the Flash Player plug-in is embedded. This process works in all browsers. You can also
have Flash send variables back to your HTML page, but this process often doesn’t work with all
browsers and all platforms.
On the CD- In the following examples, you can use a file on the CD-ROM named
ROM circus.fla. Copy it to your hard drive and then publish it to get the files
circus.swf and circus.html. You’ll be modifying the HTML page
code inside circus.html quite extensively. The Flash file contains no
ActionScript; it just contains two text fields in Frame 1 referencing the
variable names clown1 and clown2.
The complete code for the HTML would look like this:
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash
page 41
Server-Side Flash: Scripts, Databases, and Dynamic Development
Adding variables to the end of a filename is a great way to simply define some variables externally and
have them available in Flash. But this method has two minor disadvantages:
You have only one chance to define the variables because they are forced into Flash
only when the plug-in is embedded in the HTML page. During later playback of your
Flash movie, you’ll have to use loadVariables to get any more external variables,
unless you employ the JavaScript methods outlined in the next section.
All your variable names and values are visible to the world! Anyone can view the
source on your HTML page to see what variables you’re defining and what values
you’re associating with those variables. Do not use this method for any variables that
you need to keep secret and secure; instead use loadVariables and some server
scripting to keep everything top secret!
As long as you’re aware of the limitations involved using the HTML query string method, you can figure
out when and where the appropriate variables you need to have ready and waiting in Flash will be there
for you.
Just like in the HTML query string, as soon as you set the variables using JavaScript, they are available
on the main timeline whether Flash has asked for them or not. The great thing about using JavaScript is
that you can set the variables after the Flash movie has already loaded.
First you need to set up the <object> and <embed> tags in the HTML page to make sure they reflect an
object name that you’ll be using to target your movie. Both these tags have a parameter that lets you
specify an object name for your Flash movie. We’ll use the circus and clown example again where the
Flash movie is circus.fla and the variables and values clown1=Happy and clown2=Honker are to be set
in Flash. The following code shows where to set the object name:
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash
/swflash.cab#version=5,0,0,0" WIDTH=400 HEIGHT=300 name="circus">
<PARAM NAME=movie VALUE="circus.swf"> <PARAM NAME=quality VALUE=high>
<PARAM NAME=bgcolor VALUE=#FFFFFF>
<EMBED src="circus.swf" quality=high bgcolor=#FFFFFF WIDTH=400 HEIGHT=300
name="circus" TYPE="application/x-shockwave-flash"
PLUGINSPAGE="http://www.macromedia.com/shockwave/download
/index.cgi?P1_Prod_Version=ShockwaveFlash"></EMBED>
</OBJECT>
page 42
Server-Side Flash: Scripts, Databases, and Dynamic Development
In bold inside the code are the two places where you’ll need to manually add the name you’d like to
create for your Flash movie object to reference with JavaScript. Note that these places are right after
where the WIDTH and HEIGHT are specified by the <object> and <embed> tags. In this example,
circus is specified because the name of our hypothetical SWF file is circus.swf. Do not confuse
specifying this object name in the page with any of the <PARAM NAME> tags. They are different. You
can also name the object anything you’d like but be sure to enclose the specified name in quotations, as
in name="circus".
To set a variable on the main timeline of the file named circus.swf in the preceding code, you just have
to reference it with some kind of JavaScript action or function. In general, you could include this
JavaScript from anywhere inside the <body> tag after the Flash plug-in code on the HTML page:
<SCRIPT LANGUAGE=JavaScript>
document.circus.SetVariable("clown1","Happy");
document.circus.SetVariable("clown2","Honker");
</SCRIPT>
This code would immediately set two variables on the main timeline of the Flash movie referenced by
the object circus, which is circus.swf: one variable with a name of clown and a value of Happy and
another variable named clown2 with a value of Honker. The important thing to watch out for when using
JavaScript (like any language) is punctuation and capitalization. Make sure you specify the correct
object reference in between the words document and setVariable. Also, note that the variable name is
enclosed in quotations as well as its value. The variable name must always be in quotations, and the
variable’s value should be in quotations if it’s a string. If it’s a number, you can leave out the quotations,
as in the following HTML example:
<SCRIPT LANGUAGE=JavaScript>
document.circus.SetVariable("clown1",56);
</SCRIPT>
You can also reference any other JavaScript variable and send that to Flash as well by using the same
Javascript variable name or a different name, as shown in this HTML example:
<SCRIPT LANGUAGE=JavaScript>
var nameOfClown="Happy";
document.circus.SetVariable("clown1",nameOfClown);
</SCRIPT>
This code sets the JavaScript variable nameOfClown to the string value Happy and then passes that
value to the Flash variable clown1 through plain old JavaScript.
Using JavaScript to set variables in Flash can come in very handy. If you’re very familiar with
JavaScript, you could have HTML page form values that can be sent into Flash, or you could put the
SetVariable statements inside a JavaScript function in the <head> tag, call the function in the <body>
tag with onLoad, and continually pass data into Flash. That’s right, you can open a pipeline right into
Flash through JavaScript and continually feed Flash new and updated information by using the
JavaScript SetVariable. Be sure to coordinate elements in your Flash movie so Flash can do something
with the data as it’s arriving.
Caution The one drawback to using JavaScript to send variables to Flash is that
anyone can see what you’re up to by viewing source on your page. Most
people surfing the Internet won’t have a clue, but if any security issues are
involved, you should keep things inside of Flash using loadVariables and
server scripting. For simple things and fun Flash movies it’s a great tool to
have in your bag though!
page 43
Server-Side Flash: Scripts, Databases, and Dynamic Development
want to call. If you defined a Javascript function named dateAndTime() in the HTML page holding your
Flash movie, for example, and you wanted a button in Flash to execute it, the Flash button code would
read:
on (release) {
getURL ("javascript:dateAndTime();");
}
No space follows the colon in javascript: and that the semicolon for the JavaScript call is enclosed within
the quotation marks of the getURL action where the URL would normally go.
In addition to calling a predefined JavaScript function, you can also use Flash to execute just about any
valid JavaScript. You need to format the statement correctly because the Flash getURL action needs
quotation marks in the right place as well as the JavaScript code. Suppose that you need a button in
Flash to set a JavaScript variable in the HTML page named clown1 to a value of Happy. The Flash
button code would read:
on (release) {
getURL ("javascript:var clown1=\"Happy\";");
}
Notice the odd looking sets of quotations and semicolons near the end of the statement. The escaped
quotation mark \" is needed to make sure that Flash is sending that quotation out to the HTML page and
not interpreting it as a quotation signifying the end of the URL parameter in the getURL action. The last
quotation in the statement signifies this and is not preceded with a backslash. Immediately following the
last quotation is the closing parenthesis for the getURL action and then the ending semicolon for the
Flash statement. The ending semicolon for the JavaScript statement is the one that follows Happy\" in
the code line.
Stand-alone only
I bet you’re just ecstatic about this! This action opens the door to create stand-alone applications in
Flash that can save data on a user’s hard drive and retrieve it later on. You could build dynamic stand-
alone projector games that save a player’s high score and current place in the game or design a Flash
multimedia kiosk application for a trade show that will let viewers register and be able to retrieve their
names after the show! However, this secret action works only with stand-alone projector files with the
exe or hqx extensions and not from the Web or in a Web browser.
This quick example will immediately create a text file on your hard drive and write some variables to it:
1.Create a new Flash file named secretFS.fla and save it on your local hard drive.
2.Select Frame 1 of this new Flash file and add the following frame actions:
3. author1="Mark Winstanley";
4. author2="Bill Sanders";
publisher="Hungry Minds";
5.Create a button on the stage in Frame 1 or drag one from the Standard library by
choosing Window → Common Libraries → Buttons.
6.Attach the following ActionScript to the button:
7. on (release) {
8. fscommand ("save", "fs_data.txt");
}
9.Under File → Publish Settings, check only the box for either Windows Projector or
Mac Projector. Leave all the other boxes unchecked.
10. Press F12 to quickly launch the projector file. Click the button.
11. Using your Windows or Macintosh OS, navigate to the folder where you saved
secretFS.fla and you’ll see the fs_data.txt text file.
page 44
Server-Side Flash: Scripts, Databases, and Dynamic Development
If you take a look at this data, you’ll notice that the variables contain the proper ampersands (&) and
equal signs (=), but they lack any other URL encoding such as converting the spaces between our first
and last names into plus signs (+). Flash doesn’t bother to convert spaces or any other nonletter
characters for that matter into their URL-encoded equivalents. Flash knows that these characters are
only going on a local hard drive and are not being sent out over the Web, so it skips that step.
Specifying a path
Now you can save variables to anyone’s hard drive who happens to be viewing the projector movie you
created. You can also specify any path you’d like for the text file containing the variables. If you don’t
specify a path, Flash automatically creates the text file in the same directory as the projector file. You
could specify the parent directory of that file with this code:
fscommand ("save", "../fs_data.txt");
You could also specify any direct path on the hard drive:
fscommand ("save", "C:/My Documents/fs_data.txt");
Notice that example uses a Windows hard drive path. We don’t know at this time what the correct paths
may be for a Macintosh system and whether specifying a path on the Macintosh works. On Windows
however, if you specify a path to a drive or folder that already exists (Flash can’t create a directory),
Flash will place the generated text file in that directory.
Also notice that normally on a Windows operating system the path to My Documents uses backslashes
(\) and looks like the following:
C:\\My Documents\
Flash on the other hand finds its way to any directory on the hard drive using forward slashes (/) similar
to a Web directory:
fscommand ("save", "C:/My Documents/CoolGames/gamedata.txt");
or
fscommand ("save", "C:/My Documents/flashdata.html");
There isn’t much of a reason to specify any extension other than txt unless another program running on
the same machine uses the data, as in the case of a multimedia kiosk.
page 45
Server-Side Flash: Scripts, Databases, and Dynamic Development
never find it, and therefore can’t delete it. Use these features with fairness and respect and you’ll never
have anyone complaining that you’ve done sneaky things on their hard drive. Have fun!
Summary
Throughout this chapter, we have covered many facets of data formatting and sending and receiving
that data to and from Flash. Go through the examples presented in this chapter carefully so that you’ll
be prepared to deal with data transfer in the later chapters. Many things presented in this chapter are
basic Internet principles as well, and you’ll now have a better understanding of the types of things that
go on behind the scenes as data flies across the Internet. For those of you who are old hats at server
scripting, you now see the ways that Flash deals with URL-encoded variable loading and sending along
with its caveats and peculiarities. You’re now ready to move onto the server languages and start making
Flash truly dynamic and interactive!
CGI scripts are the quickest and easiest way to add interactivity to your Flash movies and your Web
site. These scripts can send e-mail messages, set and retrieve cookies, read and write to and from text
files, and provide you with added security. CGI is the most common form of interactivity found on most
Web host servers and is widely supported across the Internet. In this chapter, the many parameters and
setup requirements that are unique to CGI are explained in detail. Once you get a few scripts up and
running, you’ll be using CGI all the time to enhance your Flash sites and make them perform amazing
interactive feats!
Using CGI
CGI and Perl are almost always found exclusively on Unix or Linux Web servers. Perl scripts can be
utilized on Windows NT hosts, but they require special modules. In contrast, installing Red Hat Linux on
a Web server automatically installs Perl and makes the server ready to start executing any Using Flash
and CGI/Perl to develop applications that check passwords, write and read text files, and send e-mail
scripts. In most cases, you don’t have to worry about these details. Just ask your hosting company, “Do
you support and allow CGI/Perl scripts on your server?” Or if you are purchasing a new account, ask
that your Web site be put on a Unix or Linux Web server that supports CGI and Perl.
Perl scripts have a wide variety of uses, including interacting with various types of databases. This
interaction requires special modules regardless of the type of server software installed. Because the
focus of this chapter is quick and easy interactivity with CGI, the use of scripts to interact with mySQL is
best left to the chapters on mySQL and PHP, which has become the de-facto standard for integrating
with mySQL. Database design is also a world unto itself, and you’ll see how with CGI/Perl and a
standard text file you’ll be able to emulate many of the read/write features of a database without all the
additional setup steps. If you find Perl programming to your liking, check out Perl for Dummies, 3rd Ed.
by Paul E. Hoffman (IDG Books, 2000) or Perl: Your Visual Blueprint for Building Perl Scripts by Paul
Whitehead and Eric Kramer (IDG Books, 2000) for more information on the intricate details of this
language.
Cross- To learn more about writing server scripts for MySQL and PHP, take a
Reference look at Chapter 4, “Using Flash 5 with PHP4 and MySQL.”
page 46
Server-Side Flash: Scripts, Databases, and Dynamic Development
A Perl script is just a list of programming instructions inside a text file for the server to read and then
execute. You can use any common text editor, such as Notepad or Wordpad (Windows) and
SimpleText (Macintosh), to create a Perl script. You could use a more complex program, such as Word,
although the file must be saved in plain text format with the extension pl added to the end. For
example, you’ll be creating two Perl scripts in this chapter named setCookie.pl and getCookie.pl.
Note To modify a Perl script from this chapter that is on the CD-ROM, you first need to
transfer the script to your hard drive and then upload it to your Web server. You
may even want to copy all the Flash FLA files and all the Perl PL files to a new
directory on your hard drive and open them from there.
Uploading and configuring Perl scripts on the server is a two-part process. The first part is to upload
your script file into the cgi-bin directory; this process is no different than uploading any file to your
Web server. Open up your favorite FTP program and upload the file just like any other Web page or
graphic file.
Caution Using an FTP program to upload your Perl scripts is important. Uploading a
Perl script to your Web host by using a program such as FrontPage or
Dreamweaver is not recommended because most programs like these usually
do not support the configuring of your script. Make sure to always select ASCII
format in your FTP program as well. Most FTP programs upload in a binary
format by default, but you want to upload Perl scripts using ASCII. The
documentation for your FTP program can help you properly configure the
program for this format.
page 47
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 2-1: Accessing the CHMOD window to configure Perl scripts in the FTP program CuteFTP.
Each CGI script you upload has to be individually configured with a CHMOD command to designate what
the server is to do with it when it receives a request for that file. The CHMOD command is followed by a
three-digit number that represents the type of permissions to be set. The two you need to know are 755
and 666.
CHMOD 755 represents the permissions to set for a CGI script that you want the server to execute and
then provide you with an output. CHMOD 666 is the permission to set for a data file that is going to be
updated and written to by another script. Almost all scripts will be CHMOD 755, unless they contain raw
data that needs to be dynamically updated; in those cases, the file will be CHMOD 666. Files that are
CHMOD 666 usually contain nothing but data and end in the extension dat or txt, which marks them
as dynamic text files. When a file’s permissions are set to 666, the server is allowed to dynamically write
to a text file. Figure 2-2 illustrates how this process works on the server and returns data to Flash.
Figure 2-2: The process of Flash working with multiple scripts and text files on the server.
Note Each script you upload needs to be individually configured with the CHMOD
command for its intended purpose. The server, however, stores these permission
settings as an association to the filename. This means that when you first upload
a script you must use CHMOD, but when you upload revisions to the script, you
do not need to use CHMOD again as long as the filename is the same. This takes
page 48
Server-Side Flash: Scripts, Databases, and Dynamic Development
the hardship out of making lots of changes and then quickly uploading and testing
their effects.
You may run into a few problems when you initially contact your hosting company about using CGI with
Perl scripts. One common problem is that your host does not allow CGI use at all or allows you to use
only the prewritten scripts it has made available to you. If you have this problem with your host and you
are paying for this hosting, switch immediately to a better company! Hosting companies today have no
excuse for not allowing their users access to CGI/Perl other than incompetence on their part and lack of
knowledge on how to properly protect their servers (because CGI can present somewhat of a security
risk).
Tip A great hosting company like jtlnet.com is the place to go for good service at a
reasonable cost. With accounts starting at $7.95 per month, this company provides
full CGI/Perl support along with PHP 4.0 and mySQL. We are baffled as to why
other hosts give their paying customers a headache concerning CGI.
Another problem may occur after you’ve uploaded your scripts to the designated cgi-bin directory and
are unable to use the CHMOD command with the files. This problem usually occurs when a host has
given you limited CGI access because setting certain file permissions might wreak havoc on their
servers. Full CGI access would allow you to run executable scripts such as CHMOD 755 because this
server is generally configured to automatically execute all scripts in the CGI directory. The downside to
having limited CGI access is that you cannot designate DAT files to write and append data to. Unless
you’re intimately connected to a host like this, we suggest seeking a different host or asking the host to
give you a CGI directory with full access to file permissions. You would be surprised how many hosting
companies with multimillion-dollar clients have these problems. Educating your clients is a good way to
get them to switch hosts, especially when the result is a dynamic, interactive Web site.
Tip You can also set CHMOD permissions with Telnet. Fewer and fewer hosts allow
Telnet access these days, but if you can find one (like jtlnet.com), the com- mand
once you change to the right directory is chmod 755 filename where filename is the
name of your Perl script or dat file.
page 49
Server-Side Flash: Scripts, Databases, and Dynamic Development
The small script you’ve just written contains the very basics of a Perl script that you will use to integrate
with Flash!
Perl syntax
To ensure your scripts properly execute, you must follow some simple rules. Let’s dissect some lines of
code in testing.pl to see the basic syntax rules required for a properly functioning Perl script.
Path to Perl
All Perl scripts must begin with this line that designates the path to Perl. This line always begins with the
two characters #! and does not need a semicolon at the end:
#!/usr/bin/perl
The path to Perl is the location on the server where the Perl program is installed and waits ready to
parse Perl scripts. The path shown here is the normal default for most servers. If testing.pl doesn’t
work after you install it and you’re sure you’ve used the CHMOD command correctly, the path to Perl on
your server may be different. E-mail or call your hosting company to find out the correct path to use.
Semicolons
All lines of code in Perl must end with a semicolon. For example, look at the command in testing.pl
that sets a string named somenumber to be equal to 5:
$somenumber=5;
If you forget even one semicolon, the Perl script will probably not function.
page 50
Server-Side Flash: Scripts, Databases, and Dynamic Development
Comments
All comments in Perl start with the pound sign (#), as you can see in the following example:
#This sets a variable we can access
A comment line is an exception to the semicolon rule in Perl. Comment lines do not need a semicolon at
the end. Comment lines can also contain many pound signs in a row (######) to block off an area of
code.
Comments in Perl in this chapter are provided for convenience; they are not required for the code to
function properly. When you start modifying the scripts or making your own scripts, add as many
comments as you deem necessary.
Content-type
Another essential line of code is the content-type line.
print "Content-type:text/html\n\n";
In order to display data on a Web page or get it back into Flash correctly, you must set the type of data
you are outputting. In this case, we are specifying in the script that the output of our script is meant for
use on the Internet in a text or HTML format. If you view the source code on the Web page when you
execute testing.pl, you’ll see that this line is nowhere to be found because it is a necessary
scripting element and not something being output to the Web page.
Print command
The command most commonly used for displaying data is print. The print command is used to not
only display data from Perl on Web pages or to send data to Flash, but also to write data into e-mails
and text files generated by Perl. These lines are standard print statements in Perl that write data for
output:
print "This is where we can send some data to Flash<br>";
print "For example the number $somenumber";
These print statements wrote the two lines that were displayed on your Web page. Notice the
quotation marks at the beginning and end of the text to be displayed and the semicolon at the end of the
statements; these elements are required.
Also note how the $somenumber statement was included and parsed to display the number 5 on the
Web page from within the print statement. Unlike in ActionScript, you don’t need to concatenate
variables with quoted text in Perl to display multiple data types together. Perl recognizes strings present
within a quoted print statement.
Suppose you had a variable named pet and you wanted to set its value as Jaguar and display this
output:
Jaguar=A great pet to own.
The ActionScript syntax and Perl syntax for this example would look different. Here is the Perl code:
$pet="Jaguar";
print"$pet=A great pet to own.";
The same effect in ActionScript code with a text filed named output on the stage:
_root.pet = "Jaguar";
_root.output = _root.pet+"=A great pet to own."
Escaping characters
Perl automatically parses strings within print statements because it searches for the dollar sign ($)
and then parses the string that follows. If you wanted to output a dollar sign in a print statement, you
must use an escape character. In this case, you would precede the dollar sign with a backslash (\). For
example, to output the following line in Perl
I like to make lots of $MONEY$
you would need to escape the dollar signs so Perl doesn’t think MONEY is a string needing to be parsed:
print"I like to make lots of \$MONEY\$";
page 51
Server-Side Flash: Scripts, Databases, and Dynamic Development
Knowing when to escape a character is important to keep Perl from getting confused. The standard rule
is that anywhere you need to output and display a Perl reserved character such as a quotation,
semicolon, or dollar sign, you must precede the character with a backslash. The same rule applies to
certain characters in ActionScript as well.
Exit
The exit statement is always the very last line in a Perl script:
exit;
Make sure this statement always ends up at the very bottom of your script.
page 52
Server-Side Flash: Scripts, Databases, and Dynamic Development
The hash array as a whole is defined using the percent sign (%), and then values are retrieved using
the dollar sign ($) preceding the name of the whole array along with curly braces and apostrophes to
denote the key. To define a hash array and then display an element from it, you would use this code:
%carColors = ("Camaro","Red",
"Mustang","Blue",
"Corvette","Yellow");
print"$carColors{‘Corvette’}";
or
%carColors = (Camaro => "Red",
Mustang => "Blue",
page 53
Server-Side Flash: Scripts, Databases, and Dynamic Development
Individual elements in this hash array can then be changed with this code:
$carColors{‘Corvette’}="White";
In these examples, the words Corvette, Camaro, and Mustang are keys in this hash array, and
carColors is the name of the entire array. A key can be referenced with another variable, in which
case the apostrophes are not used:
$someCar="Mustang";
print"The color of the $someCar is $carColors{$someCar}";
Unlike ActionScript, Perl is case-sensitive. For ActionScript, the following variables are treated as the
same:
SalesTax
Salestax
SALESTAX
However, all of these variables are different in Perl. So you should make sure that all the ActionScript
variables you are using in conjunction with Perl are case-sensitive. That way, you won’t run into a
problem because you expect a variable named $Salestax to read your ActionScript variable named
SalesTax. Other than case-sensitivity, other naming conventions are pretty much the same in
ActionScript and Perl. For example, the Hit_Score variable in ActionScript will be equated with the
$Hit_Score variable in Perl.
The information in these variables is always available as long as the data exists. (If no cookies have
been set, there are obviously none to retrieve.) To retrieve data in any of these variables, use the
following syntax:
$ENV{‘environment_variable’}
For example, to find out where the current script was called from, write a Perl script in your text editor
containing the following code:
page 54
Server-Side Flash: Scripts, Databases, and Dynamic Development
#!/usr/bin/perl
#This displays the URL from where
#this script was called
print "Content-type:text/html\n\n";
print "This script was called from $ENV{‘HTTP_REFERER’}";
exit;
Name the script environment.pl, upload it to your server, and configure it withCHMOD 755. Now
create a simple HTML Web page with a link to this script. Upload this Web page to the normal place on
your host where Web pages are stored (or, even better, another domain if you have one). Open your
Web browser and surf over to this page. Click the link you created to your script. The page should
display the URL of the HTML page from whence you came. This script is on the CD-ROM.
These environment variables are powerful tools not only for seeing the data they contain but also to test
for certain conditions such as whether cookies exist or if the script was called from only a particular Web
page on your server. Knowing this information could help you prevent people from calling your scripts
from their own Web sites or from their desktops. We will be making good use of these environment
variables.
if ($ENV{‘REQUEST_METHOD’} eq "GET"){
print"$ENV{‘QUERY_STRING’}";
}
elsif ($ENV{‘REQUEST_METHOD’} eq "POST"){
read(STDIN, $allPostData, $ENV{‘CONTENT_LENGTH’});
print"$allPostData";
}
exit;
Return to Flash and preview the movie in your Web browser while you’re connected to the Web. Type in
any colors (or words for that matter) in the text fields and click the Send button. A window will pop up
page 55
Server-Side Flash: Scripts, Databases, and Dynamic Development
showing the variables in one long string, which is how Flash sent them to the Perl script. Potential
results are displayed in Figure 2-4.
Figure 2-4: Perl displays all your variables from Flash exactly the way it received them, in one long string.
Notice the environment variable is tested for to determine GET or POST and then either the query string
(QUERY_STRING) or the post header (CONTENT_LENGTH) is subsequently displayed. Change the code
in the Flash movie Send button to reflect the POST method and test the script again in your Web
browser. The same script recognized the method as POST and displayed the same data as it did using
the GET method.
This following line is necessary in Perl to extract data from the post header.
read(STDIN, $allPostData, $ENV{‘CONTENT_LENGTH’});
It takes the data in the post header and sticks it in a variable named allPostData. You can replace
this variable name with anything you want for referencing later in the same script. The rest of the line
must remain as is.
Keep testing the script using characters such as spaces, ampersands, and asterisks in the text fields.
Try leaving every other field blank. Try leaving all the fields blank or just one. Every time you click Send,
the script throws the data you sent right back at you ‘as is’. In order for Perl to operate individually on
those variables, you need to break up that big long string.
Perl looks at the query string or post header sent by Flash as being one big lump of data, one whole
string. When Flash receives such data, it is smart enough (thanks to Macromedia) to be able to sort
through the data and automatically separate it into individual variables. Perl can do this task, too, but
you must write your own routine for it. In the following exercise, you will see how you must program Perl
to take the incoming singular data stream and divide it up into individual variables.
Open the CD-ROM file colorsplitter.pl in your text editor (see Listing 2-1). Upload the file to your
server and configure it as CHMOD 755. Change the ActionScript in the Flash button labeled SPLIT UP
to reflect your Web domain. Save your changes to your hard drive; you’ll be using this file again.
Listing 2-1: The colorsplitter.pl File
page 56
Server-Side Flash: Scripts, Databases, and Dynamic Development
#!/usr/bin/perl
print "Content-type:text/html\n\n";
if ($ENV{‘REQUEST_METHOD’} eq "GET"){
$allWebData=$ENV{‘QUERY_STRING’};
$value =~ tr/+/ /;
$DATA{$name} = $value;
Test the Flash movie in your browser and click the SPLIT UP button to see what happens. The result
should look like what is displayed in Figure 2-5.
page 57
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 2-5: Results of the variables from Flash being split up and displayed on a Web page.
Note The results may not be listed in the order that you’re viewing them in Flash. The
reason for this is that the Perl script deals with the variables in a random order,
not the order they’re graphically displayed in your Flash movie. For the purposes
of this book, this difference doesn’t matter because eventually you’ll just be
sending them back to Flash, not to a Web page for a listed display.
page 58
Server-Side Flash: Scripts, Databases, and Dynamic Development
Foreach
The foreach command goes through every value in the array specified in parentheses and performs
the operations inside the curly braces on each value. The syntax of the foreach statement is
Foreach $item (@array_name) {
#Perform some action here on each item by referencing $item
#You can rename $item to any name you want as long as it’s
#a name you again reference inside these curly braces
}
Back to our example, the temporary holding variables $name and $value are each assigned one half
of each pair in the array, which happens to be each variable’s name and its value:
foreach $pair (@variables) {
($name, $value) = split(/=/, $pair);
The translate function and a regular expression then convert all spaces back into themselves and
change special characters that were URL encoded into themselves (on the value side of each pair):
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
The last line of the foreach statement loads the final, usable name and value variables into a hash
array:
$DATA{$name} = $value;
Notice the mixed use here of variable names that are already defined being loaded into an array that is
undefined. In Perl, you don’t need to define variables, arrays, or hash arrays before you use them. In
this code, the new hash array %DATA is being loaded one value at a time with the predefined variable
name from Flash, which happens to be the hash array’s key ($name) and its value ($value). For
example, you could now rename favColor1 by inserting
$DATA{‘favColor1’}="Pink";
after the closing curly brace of the foreach statement.
Keys
Keys are the name part of an associative hash array, as shown in the following string:
$arrayname{$keyname} = $somevalue;
The last section of colorsplitter.pl uses foreach along with a reference to each key to go one
by one through the hash array and display the variable name and its value. The reserved word keys in
Perl references each key in the array name following it, in this case %DATA:
# Display the final output on the Web page
foreach $i (keys %DATA) {
print "$i: $DATA{$i} <br><br>";
}
Note The <br> tag is used here for Web page display only and inserts standard line
breaks to separate the data. When dealing strictly with Flash, you don’t need to
include tags like these, and they’re here just to illustrate basic concepts. Any data
sent back to Flash will have to be sent back in the form of a query string, in one
piece, with no line breaks in between.
To illustrate how Perl can now treat the variables on an individual basis and operate upon them, change
the last section of code in colorsplitter.pl to read
foreach $i (keys %DATA) {
page 59
Server-Side Flash: Scripts, Databases, and Dynamic Development
These examples are here to show you what is going on behind the scenes with Flash and Perl and how
Perl must divide up data in order to deal with it effectively. Sometimes breaking up the data is
unnecessary, but you must know how it works, nonetheless. You have been displaying the output of
your CGI/Perl scripts so far in a pop-up window to illustrate what Perl is doing to all the data. We can
now move on to seamlessly and invisibly sending the data back into Flash from Perl to create a truly
dynamic Flash experience!
Sending data back to Flash from a Perl script is now as simple as deciding what you want to do to the
data in Perl and then making a minor formatting change so Flash can read it. Your Perl script can send
back brand-new data that is either dynamic or hard-coded into the Perl script itself.
Cross- Flash can read text files! In Chapter 1, we discuss how to get Flash to
Reference read data from a text file. We’re doing the exact same thing here except
that the text file is being dynamically generated by Perl each time it is
called.
page 60
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 2-6: The data has made its way back to Flash after being modified by Perl.
When you press the SEND BACK button, the following happens:
Flash converts all the favColor variables to URL encoding and sends them to the
Perl script.
The Perl script on your host server receives the variables and separates them.
The Perl script then prints a text file, which is invisible to the user, with the new data
in a format Flash can read.
Flash reads this data and replaces the existing variables with the changed ones.
page 61
Server-Side Flash: Scripts, Databases, and Dynamic Development
The important factor in getting Flash to recognize the returned data is this print statement:
print "$i=The color is $DATA{$i}\&";
It references each variable’s name with $i and prints the equal sign (=) followed by some text and the
actual variable value referenced by $DATA{$i}. The very last and most important piece is the escaped
ampersand (\&) at the end. This escaped character enables all the variables to be strung together in the
query string format Flash is happy to read.
Tip If you experience a problem at any time when you test Perl script outputs for
invisible return into Flash, just change the loadVariables statement in Flash into a
getURL with a _blank window target. This change will display exactly what is being
sent to Flash in a pop-up browser window and allow you to make corrections to
your Perl script if it’s not printing the final variable list correctly. It’s a valuable tool
for troubleshooting.
At the end of the returncolors.pl file, right before the print statement, try inserting this statement
$DATA{$i}.=$DATA{$i};
or this one
$DATA{$i}+=$DATA{$i};
page 62
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 2-7: Perl has taken all the variables and renamed them, attaching the same values, and sent them
back to Flash.
Save and upload your script changes and test the Flash movie in your browser. When you click the
SEND BACK button, Flash still sends all the data to the Perl script. But after the Perl script splits the
data, it chooses to ignore it and return something completely different to Flash. This process is how you
would test in Perl if a password you’ve defined in Perl matches one that a user submitted through Flash
and then returned an approval or denial. We’ll discuss this topic in more detail in the next section. For
now, congratulations on successfully completing the basics of integrating Perl with Flash! Let’s move on
to some great dynamic applications with our dynamic duo: Flash and Perl
page 63
Server-Side Flash: Scripts, Databases, and Dynamic Development
code specific to the objective, and some new commands are introduced; however, most of the code
should be familiar from the previous sections.
Checking passwords
Checking for passwords is a common feature on many sites to keep out unwanted visitors or to direct
specific visitors to a certain section of your Flash site based on who they are. One way to do this is by
creating a text file of all the passwords, loading the file into Flash, and then using Flash to search
through and match each one against a password submitted by the user. The big downside to doing it
this way is that this process is not very secure. Because the call for the text file containing the
passwords was made through an HTTP request, that text file is now in the user’s browser cache and he
or she can easily open up his or her cache and view all the passwords along with any other variables
you’ve stored.
Security has become even more important since the Flash Player SDK was released because many
companies have come up with ways to compromise the security of compiled and published Flash
movies. Available programs can reveal all of your ActionScript code and target names for the entire
world to see, regardless of whether you’ve checked the Protect From Import option. This capability
represents a huge security risk for your Web site and Flash movie. If this problem sounds farfetched,
just check out the ActionScript Viewer from www.buraks.com and see what I mean. This program
shows anyone the entire contents of your Flash movie. Server-side scripting takes on a whole new level
of importance in keeping sensitive information away from the prying eyes of unscrupulous individuals.
Perl to the rescue! The simplest way to strengthen security around passwords or other sensitive
dynamic data is to make sure it all stays on your server where it belongs. Perl receives a password
submitted by a user through Flash and compares it to an array list of all passwords. Perl then
determines if a match exists and returns a simple approval or denial message. The user never sees
anything except this final answer. The details surrounding the processing of the question happen on
your Web server where the user never sees or knows precisely what is going on. Even if the user types
a direct URL to your script, he will only get the cake and never the recipe!
On the CD- In the following exercise, you’ll use a Flash movie file called simple_login.
ROM fla and Perl scripts named simple_login.pl and perltemplate2.pl. You’ll find
these files on the CD-ROM located at the back of this book.
In this example, you’ll see how a Perl script is used to integrate password protection into a Flash movie.
Follow these steps:
1. Open the Perl script simple_login.pl on the CD-ROM and upload it to your server
using CHMOD 755.
2. Open the Flash file simple_login.fla on the CD-ROM.
3. Change the LOGIN button loadVariables ActionScript to reflect your Web domain.
4. Test the Flash movie in your Web browser.
5. Enter different passwords and observe the denial message.
6. Enter either Winstanley or Sanders for the password and you will see the word
ACCEPTED!
You have just observed passwords being checked by Perl and only the approval or denial being
returned to Flash. To take an in-depth look at all the code, open simple_login.pl in your text editor
and notice that it uses the standard input parser that has been present in many scripts up to this point.
The CD-ROM file perltemplate2.pl contains these core parsing pieces, and we’ll be using them in
most scripts from here on out. Take a moment to look at perltemplate2.pl. It contains a
commented main code section, which is where you should put your main body scripting elements.
The simple_login.pl script uses the standard elements in perltemplate2.pl to separate out all
the variables. The main code section utilizes the following code to define the passwords, check for a
match, and then send an approval or denial to Flash:
#Define the password array and then test user input
@passwords=("Winstanley","Sanders","Flash5","ActionScript");
$approval="no"; #Set a flag to reflect a nonmatch#
foreach $checkme (@passwords){
if ($DATA{‘userPassword’} eq $checkme){
$approval="yes";
#Set flag to true if a match
page 64
Server-Side Flash: Scripts, Databases, and Dynamic Development
print"approved=$approval";
#Print the variable ‘approved’ to Flash
#containing either yes or no
The Flash movie contains only one input text field named userPassword. This input is sent out to Perl
where the preceding coding section checks for a match. During this process, Perl performs these
actions:
1. Defines the master password array in @passwords
2. Sets a flag named $approval to its default no before it starts checking for matches
3. Starts checking each password defined in Perl in @passwords against the variable
userPassword sent from Flash that was defined inside the DATA array in the
standard parser section
4. Prints back to Flash the variable name approved followed by an equals sign and
then a value of yes or no held in $approval
Flash receives this data and then decides, based on the approval variable being yes or no, whether to
accept or decline the user access to the site.
page 65
Server-Side Flash: Scripts, Databases, and Dynamic Development
come back from Perl. However, the variables that are sent are on the main timeline because the main
timeline is where the button sits and where the statement is executed from. The only variable existing
on the main timeline is the userPassword field, which Flash whisks off to the server.
The onClipEvent(data) statement on the _root.process movie clip patiently waits the whole time
to receive any variables. When it receives a variable, it executes the if(this.approved eq "yes")
statement to check whether an approval was sent from the Perl script. This movie clip then sends itself
to the appropriate frame. As with anything in Flash, you can house and nest these movie clips in a
number of ways. This is just one.
Now your main timeline is jumping to a new place instead of the Process movie clip moving its timeline.
You could change those statements to reflect anything you’d like to happen in Flash when someone is
approved or declined based on their password. Now the Process movie clip is nothing but a robot clip
whose job it is to wait for variables and then redirect the main timeline. You can easily hide a movie clip
like this off the main stage while it waits to accept and process data.
On the CD- In the following exercise, you’ll use a Flash movie file called
ROM complex_login. fla and the Perl script named complex_login.pl.You’ll find
these files on the CD-ROM located at the back of this book.
A more complex variation of this project is to have Perl check for both a username and a password. This
variation is illustrated in the files complex_login.fla and the Perl script complex_login.pl that
accompanies it. The only change in the Flash movie is the addition of a text box on the main timeline
with the variable name userName. The Perl script looks very similar except for some changes to the
last processing section:
# Define the password array and then test user input
%passwords=(Mark => "1234",
Bill => "AABB",
Mike => "XYZ"
#Add more usernames and passwords here
);
$approval="no"; #Set the flag to ‘no-match’#
foreach $name (keys %passwords){
if ($name eq $DATA{‘userName’} && $passwords{$name} eq $DATA{‘userPassword’}){
$approval="yes";
#Set flag to true if a match
#between both userName and userPassword
}
}
print"approved=$approval";
#Print the variable ‘approved’ to Flash
#containing either true or false
exit;
In this case, the usernames are the keys in the %passwords array. The foreach and if statements
then make sure that when and if a valid username is entered, it is matched against its associated
password on the value side of the %passwords array. This coding delves deeper into the world of Perl,
and an in-depth explanation is beyond the scope of this book. The good thing is that you can use this
page 66
Server-Side Flash: Scripts, Databases, and Dynamic Development
script as-is in all your Flash movies. Just add more usernames where the commented line says to do
so. The syntax is as follows:
username => "password"
Remember to add a comma after each line unless it’s the last element in the array definition, like Mike
is in the previous example.
You can use either the simple or complex login scripts along with your Web site by modifying your Flash
movie to submit the correct variable names and wait for the approved variable to return. Just be sure
to change the passwords in the simple_ login.pl script or the usernames and passwords in the
%passwords hash of complex_login.pl. Making changes and spending lots of time testing is the
way to become a true master of server interaction.
Baking cookies is an excellent way to store personalized data about someone who visits your Web site
and retrieve that data at a later time. The neat thing about cookies is that they’re not stored on the
server in any sort of database but on each user’s computer, where they stay for as long as you specify.
You can use them to create a truly personalized experience for the user without the user having to log in
to any type of database. You could store a person’s name and personal preferences that you would
then use in Flash to greet that person or configure a menu structure a certain way. Cookies are also a
great way to store a high score for each person playing a Flash game or even to track a player’s
progress and let that player return to the same area of a game he or she was playing the last time he or
she was at your site!
A cookie is nothing more than a text file containing some sort of data that is stored in a special
temporary directory on each user’s hard drive. This text file can be read by and written to via any Web
browser and, in turn, the data can be passed back and forth to Flash. A separate cookie text file is
stored on a user’s computer for each Web site he or she visits that sets a cookie. Inside that text file are
name/ value pairs, and each individual pair can be considered and referred to as an individual cookie.
Cookies have a limited time that they’re good for, which is referred to as the expiration. When asked to
read and return the data contained within a cookie, the Web browser first checks to see if the cookie
has expired. If it hasn’t, all the data within the cookie will be returned to whatever type of script was
asking for it; in our case a CGI/Perl script. Perl is a great way to set and retrieve cookie values and pass
them back and forth to and from Flash because all the scripting happens on the server side. Many times
JavaScript is used for cookies, but it’s often unreliable and exposes all your code because JavaScript is
in the HTML page. Using a Perl script via the loadVariables actions in Flash to set and retrieve
cookie values enables you to store Flash variable values on the computer of anyone viewing your Flash
movie without that person even knowing it.
Caution Most people have cookies enabled in their Web browser. Those who are
particularly security-conscious (or just plain paranoid) have cookies turned off
or have their browser prompt them each time a cookie is being set. If the
user’s cookies are disabled, you won’t be able to use your Flash/Perl/cookie
scripts when that person is viewing your site. If you need everyone viewing
your site to have access to the cookie scripts you’re using, you should place a
message on your Flash site prompting users to enable their cookies. If the
users’ cookies are set to prompt them when they are being set, those users
will know each time you’re setting a cookie via Flash, so be forewarned.
Setting cookies
The explanations of some core elements of a Perl script that effectively sets cookies in Flash are
beyond the scope of this book. Therefore, we’re going to just provide you with a great cookie script for
Flash and explain only the areas that you need to change in order to set the expiration date you desire.
Listing 2-2 outlines the code inside cookset.pl with some of the key sections in bold.
Listing 2-2: The cookset.pl Code
#!/usr/local/bin/perl
srand(time);
page 67
Server-Side Flash: Scripts, Databases, and Dynamic Development
$expiration = setGMT(time+(86400*$numberOfDays));
#################################################
if ($ENV{‘REQUEST_METHOD’} eq "GET"){
$allWebData=$ENV{‘QUERY_STRING’};
#################################################
print "Set-Cookie:$name=$value;expires=$expiration;\n";
}
###############################################
print "Content-type:text/html\n\n";
print "Cookies were just set that expire on $expiration";
##############################################
# Subroutine to set GMT expiration time
sub setGMT {
($inTime) = @_;
@monthArr = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
"Sep","Oct","Nov","Dec");
@dayArr = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
($second,$minute,$hour,$monthday,$month,$year,$weekday,$yearday,$ldat) =
gmtime($inTime);
page 68
Server-Side Flash: Scripts, Databases, and Dynamic Development
exit;
On the CD-ROM Locate the files cookset.pl, cookread.pl, and cookdelete.pl on the
CD-ROM and transfer them to your hard drive. Open cookset.pl
in your favorite text editor to examine and modify it.
The only line in this entire script you’re going to need to change is the line of code dealing with setting
the expiration date:
$numberOfDays=7; ##Replace this number with 1-365 days##
The variable numberOfDays is set to 7 in this line, meaning that the cookie will expire seven days
following the day it is set. After the cookie has expired, it disappears and is no longer readable by the
cookread.pl script, which is explained in the next section. For now, just realize that all you have to do
is replace the number 7 in this code line with any number between 1 and 365 for the number of days
you’d like the cookie(s) to remain available.
The rest of the script contains code to break apart any query string or post header sent from Flash,
break apart the name/value pairs, and set the name/value pairs as cookies on the user’s computer. You
can see from the line
print "Set-Cookie:$name=$value;expires=$expiration;\n";
that the command in Perl for setting cookies is Set-Cookie. The tricky part is the expiration date, and
that’s where the extra functions and subroutines in the script come into play to set the date in the GMT
time that most Linux/Unix servers demand. The code provided here does it all for you, so you have
nothing to worry about.
The section of code that notifies you of the successful setting of the cookies begins with the following
comment:
# Output in web browser - for testing only via getURL
The code in this section gives you a confirmation message if you’re testing the script initially using
getURL instead of loadVariables, which is a good idea.
The following steps show you how to implement cookset.pl on your Web site with a Flash movie.
When called from Flash, the script will take every variable defined in the query string or post header and
set it as an individual cookie that expires in the number of days you specify in the numberOfDays
variable.
1.Upload the cookset.pl Perl script to the cgi-bin directory on your Web server and set
its permission as CHMOD 755.
2.Create a new Flash file named firstcookies.fla and save it on your hard drive.
On the stage in the initial layer, create three input text fields and place them
anywhere you want. Use the Text Options panel to give the first text field the
variable reference var1, the second field a variable reference of var2, and the third
field a variable reference of var3, making sure to also check the Border/Bg check
box for each field.
3.Create a button on the stage or use one from Window → Common Libraries →
Buttons. (The firstcookies.fla file is available on the CD-ROM if you want to
reference it for layout or coding purposes.) Attach the following action to your
button, making sure to replace www.mydomain.com with the proper path to the
cookset.pl script on your server:
4. on (release) {
5. getURL ("http://www.mydomain.com/cgi-bin/cookset.pl",
6. "_blank", "GET");
}
7.Save your changes to firstcookies.fla and preview the movie in your Web
browser by pressing F12. Enter any values in the three fields that you want, for
example, red, green, and blue.
8.Click the button you created and a new browser window should pop-up with a
confirmation message telling you that cookies were set and they expire on the date
consistent with the numberOfDays variable set in the cookset.pl script. Here is
an example of the message that should appear:
9. Cookies were just set that expire on Wed, 18-Apr-2001 10:13:46 GMT
page 69
Server-Side Flash: Scripts, Databases, and Dynamic Development
Your cookies have now been set. You can see from the query string in the pop-up browser window the
variable names and values sent by Flash. These have now become the cookie names and values set by
the browser on your hard drive specific to the Web domain where you uploaded the Perl script. If you
entered the three colors specified in step 4, your hard drive would contain the following cookies:
Retrieving cookies
The code involved to retrieve the values of cookies that you’ve set is much simpler than the code to set
them. Open the cookread.pl file in your text editor. This code will retrieve any cookies that were set
by the server for the current Web domain and display them in a Flash-friendly format with name/value
pairs separated by ampersands:
#!/usr/local/bin/perl
print "Content-type:text/html\n\n";
###################################
#Pull in all the available cookies
$allCookies = $ENV{‘HTTP_COOKIE’};
###################################
#Output each cookie name/value pair
#with an ampersand between them
#
@cookies = split(/; /,$allCookies);
foreach $i (@cookies) {
($cName,$cValue) = split(/=/,$i);
print"$cName=$cValue&";
}
###################################
exit;
The first section highlighted in bold contains the line needed for Perl to read in all the cookie names and
values from the user’s hard drive. The big time saver in this system is the Perl environment variable
HTTP_COOKIE. Anytime a request is made to the server for a Perl script, any cookie names and values
are always present in this environment variable. All we had to do in this code is assign this variable to
the $allCookies variable and then perform a simple split action, just like the splitting of a query
string. The only difference is that the separator in this code is a semicolon, as evidenced in the following
line:
@cookies = split(/; /,$allCookies);
After the names and values of the cookies have been separated into the variables $cName and
$cValue, the only thing left to do is output them in a format that Flash can read:
print"$cName=$cValue&";
page 70
Server-Side Flash: Scripts, Databases, and Dynamic Development
You don’t have to modify anything in this script. It will find all the cookies associated with the Web
domain where the Perl script resides and output all the name/value pairs for Flash to use. Before
completing the following steps to use cookread.pl, make sure you’ve set some cookies as you were
instructed to in the last section; otherwise, there won’t be any cookies to read.
1.Upload the Perl script cookread.pl to the cgi-bin directory on your Web server and set
its permission as CHMOD 755.
2.Open the Flash file firstcookie.fla that you created in the previous section
"Setting cookies," or use the one provided on the CD-ROM. Make sure you have
used it to set some cookies.
3.Change the code on the button to the following, making sure to replace
www.mydomain.com with the path to the cgi-bin directory where you uploaded
the Perl script:
4. on (release) {
5. getURL ("http://www.mydomain.com/cgi-bin/cookread.pl",
6. "_blank");
}
7.Preview the movie in your Web browser by pressing F12. Click the button inside of
the Flash movie and a new window should pop up displaying a URL-encoded string
with the three variables you previously set as cookies.
Note You may see additional cookie names and values in the pop-up window as well.
Some could have been already set on your domain, and others may be set
automatically by the server. For example, if you are using the complimentary JTLNet
hosting account included with this book, you will see all of your previously set cookie
variables plus a variable named WEBTRENDS_ID:
8. var1=red&var2=green&var3=blue&WEBTRENDS_ID=xxxx-xxxxxxx
Note You can’t do much about something like WEBTRENDS_ID because it’s there to
automatically track server traffic. Anyway, these extra variables are nothing to worry
about unless they conflict with variable names you’re using in Flash. Your best bet is
to run this Perl script and see what kind of extra variables come back and make sure
to avoid those variable names in Flash.
9.Return to the stage of firstcookies.fla and change the button code to reflect
the following loadVariables action. This action enables Flash to invisibly load
the variable names and values provided by the Perl script that found them in the
cookies:
10. on (release) {
11. loadVariablesNum ("http://www.mydomain.com/cgi-
12. bin/cookread.pl", 0);
}
13. Preview the movie once again in your Web browser by pressing F12 and then click
the button inside the Flash movie. Within a few seconds, all the variable values
should appear in the appropriate text fields. If they don’t, make sure that your text
fields reflect the same variable references as the variable names you saw when the
browser window previously popped up in step 4.
You are now ready to set all kinds of cookies! The two scripts cookset.pl and cookread.pl
automatically set and retrieve cookies comprised of the variable names and values sent by Flash. Keep
in mind that you don’t have to attach the loadVariables action to a button; you can hide it in a frame
or movie clip action. This way, the end user usually won’t know that any cookies are being set and/or
retrieved.
Deleting cookies
Sometimes you may just want to get rid of all the cookies set for your Web domain on a user’s hard
drive. This way, you’re sure that no spare cookies are hanging around that user’s hard drive. The Perl
script cookdelete.pl on the CD-ROM will perform this task for you. The script requires no
modification or variables passed to it in order to function. Just upload it to your cgi-bin directory and
configure it as CHMOD 755.
Anytime that the script is called from a user’s Web browser via an http request, a getURL command,
or a loadVariables action, it effectively deletes all the cookies present on the user’s hard drive for
the Web domain where the script is located. The cookdelete.pl script is a combination of the two
scripts cookread.pl and cookset.pl in that it first looks for all the cookies present and then resets
them to have an expiration date of yesterday. It does this by using a negative number for the
page 71
Server-Side Flash: Scripts, Databases, and Dynamic Development
numberOfDays variable. Feel free to employ this script in any means you deem necessary because
sometimes cookies have a way of piling up.
When you first read through the capabilities of ActionScripting as presented by Macromedia, it’s easy to
get excited over the fact that you can load data in from a text file. This excitement is quickly stymied by
the fact that Flash had no way to write to a text file. A server script, such as one written in Perl, is
needed to accomplish this task because a Flash movie sits in a Web browser and a Web browser
doesn’t have the authority to go into servers and make changes to files. The instructions for making
changes must be inside a script already uploaded to the server. All Flash has to do is call out to that
script and say, “Hey, take these variables and write them to a text file!” The script then handles the
chore of opening a text file and writing the data to it.
When you append data to a file, the data is added at the very end of the last line of text currently in that
file. To open a file for appending, add two brackets before the filename in the quotation marks:
open(STUFF,">>webdata.txt");
#Opens the file for appending
page 72
Server-Side Flash: Scripts, Databases, and Dynamic Development
To read data into Perl once Perl has properly opened the text file, you assign the data to a string or
array using the file handle enclosed in brackets:
@myarray=<filehandle>;
The typical Perl print statement needs only the addition of the file handle in order to write data into the
text file. This file handle immediately follows the print statement and is not enclosed in any
parentheses, brackets, or quotes. The syntax is as follows:
print filehandle "any text here";
When you’ve finished writing to the text file, you need to close it with the close command:
close(filehandle);
open(STUFF,">>webdata.txt");
#Opens the file for appending
close(STUFF);
#Properly closes the file on the server
exit;
This Perl code opens the file webdata.txt (also on the CD-ROM) for the purpose of appending data
to it. Try it out:
1. Upload the open_close.pl file to your cgi-bin directory and configure it with
CHMOD 755. Remember that this is the script being executed.
2. Open the text file webdata.txt in your text editor just to see what it contains.
3. Upload the file webdata.txt to the same cgi-bin directory and configure it
with CHMOD 666. This code designates the text file as readable and writeable.
4. Open your Web browser and type in the URL to open_close.pl.
You should see the words The text file was properly appended. appear in your Web
browser. Hit your Refresh button three or four times. Every time you do this, Perl opens the file and then
appends the words, We are appending some text to the file, to the end of the current line.
Download webdata.txt from your Web server and open it in your text editor to view the results.
Try changing the append open command in the script to the overwrite open command by removing
one bracket. Test and view the results again and notice that no matter how many times you refresh the
script the text file contains only one line because Perl is now overwriting the entire file each time.
page 73
Server-Side Flash: Scripts, Databases, and Dynamic Development
turn opens visitordata.txt on the server and sends the information contained within this file back
to Flash. If the site viewer wants to leave his or her name and e-mail address, the viewer can enter his
or her data into the input text fields in the Flash movie and click the Submit button. The ActionScript on
the Submit button sends the new variables to writevisitor.pl on the server, which opens
visitordata.txt and writes the new information to it, replacing whatever was there before.
We’ll test this project first and then analyze the components:
1.Upload the files readvisitor.pl and writevisitor.pl to your cgi-bin folder and configure
them both with CHMOD 755.
2.Upload the data file visitordata.txt to the same cgi-bin folder and configure it
with CHMOD 666.
3.Open visitor.fla in Flash and change the loadVariables ActionScript
statement in Frame 1 to reflect your Web domain.
4.Change the loadVariables ActionScript statement on the Submit button to also
reflect your Web domain.
5.Preview visitor.fla in your Web browser.
The first thing that happens is that Flash displays default in the text fields. Flash received this data
courtesy of Frame 1 calling readvisitor.pl, which retrieved the data from the visitordata.txt
data file on the server. Even though three elements are involved in this process, it happens mighty fast.
Visitordata.txt contains only this code:
personName=default&personEmail=defualt&
The code in readvisitor.pl reads this code and sends it back to Flash by using the following Perl
code:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
open(VISIT,"visitordata.txt");
#Opens the file for reading
@visitordata=<VISIT>;
#Puts the data from the text file
#into the array @visitordata
close(VISIT);
#Properly closes the file on the server
print "@visitordata";
#Sends the data from the text file
#back out to Flash
exit;
This code opens the visitordata.txt file and puts the entire contents into the array
@visitordata. The final print statement prints the entire array in one lump back out to Flash. There
is no need to break up the data in any way because Flash automatically breaks up the data when it
receives the data. The true power in this script is that it is fully modular. You can store any amount of
variables by using this script along with writevisitor.pl!
When the user in the Flash movie wants to submit his or her own name and e-mail address, the user
types it in and clicks the Submit button, which sends this new data to writevisitor.pl, which in turn
page 74
Server-Side Flash: Scripts, Databases, and Dynamic Development
overwrites visitordata.txt with the new name and e-mail address. A brief message is displayed in
the sample file to confirm the process, and then the timeline plays through and stops at the beginning.
Here is the code in writevisitor.pl:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
open(VISIT,">visitordata.txt");
#Opens the file for overwriting
close(VISIT);
#Properly closes the file on the server
exit;
Take a look at the section that reads the query string or post header. Notice that it does not break up
the data with the split command! Herein lies the power inherent in these scripts. Perl is just taking the
entire string of data sent from Flash and writing it onto visitordata.txt. This script essentially takes
a snapshot of any data sent from Flash and pops it into the text file of your choice. Simply rename any
references to visitordata.txt to reflect the text file you wish to read/write to and make sure that
text file is configured with CHMOD 666 on the server.
If Flash sends 38 variables to this script, the script will simply take all 38 variables and put them in the
text file. The read script then retrieves all the variables and sends them back to Flash exactly as they
were sent in the first place. Flash even recognizes the URL encoding and does the proper conversions
for you when the data is returned!
I bet your mind is reeling from the possibilities now. Try out the code:
1.Inside visitor.fla, create as many more input text fields as you’d like and make sure to
name them each with new unique variable names. These text files can be as big or
as small as you’d like.
2.Preview your movie in your browser.
3.Enter any values you want in all your new text fields and click the Submit button.
4.Close your browser.
5.Download and open visitordata.txt from your server and observe the beauty of
the big, long string containing all your variables.
6.Preview the Flash movie again in your browser and notice that every variable is
exactly as you entered it!
page 75
Server-Side Flash: Scripts, Databases, and Dynamic Development
Now you have a way to read and write any amount of data from Flash with a text file. When this data
comes back to Flash, you can use it in any way you’d like.
The loadVariablesNum statement in the first frame of the movie can just as easily be attached to a
button so that a user could retrieve data on demand. Nesting the statement inside an if statement
makes for even more conditional possibilities, such as only allowing a user to write to the text file if he or
she has already logged in with a username and password.
Caution Make sure to test for the data’s existence (see Chapter 1) before operating on
it.
Even though the snapshot method was demonstrated in this example, once Perl opens your text file for
writing you can use a print statement to enter any kind of data. For example, the split command
was not used to split the incoming data string from Flash. You could easily add this code section to the
write script and write only the variables you want to a text file. This code is very useful if Flash is
sending out 15 variables and you want only two specific ones to be stored in the data text file. After
adding the split command segment, you would just change the print code block in the Perl script to
something like the following:
print VISIT "$DATA{‘personEmail’}\&$DATA{‘personAddress’}\&";
Notice the escaped ampersands (\&). These are used so that the data is stored in one long string in the
text file and later sent in one correctly formatted chunk back to Flash. If you’d like to make a text file that
keeps accumulating data, just open it for writing in append mode. Because the data already ends in an
ampersand, the file will keep accumulating data. This kind of text file can get big really fast and is not
recommended unless you plan on manually cleaning it out or writing Perl code to do it for you.
Sending e-mails from Flash is undoubtedly the most common request among those new to Flash and
server-side scripting. This example is presented last because it uses every Perl concept presented thus
far. Unlike reading and writing to text files, which involves a myriad of files, sending an e-mail takes only
one Perl script. The only new concept is using a file handle to refer not a text file, but to the mail
program on the server.
page 76
Server-Side Flash: Scripts, Databases, and Dynamic Development
E-mail requirements
Only two elements are required to send e-mail successfully: a recipient and some body text. These
elements are defined in standard Perl print statements after the e-mail program has been opened. To
specify the recipient and, optionally, a sender, reply-to, or subject, use this syntax:
print EMAIL "To: data here \n";
print EMAIL "Reply-to: data here \n";
print EMAIL "From: data here \n";
print EMAIL "Subject: data here \n\n";
Replace data here with either the actual text you are hard-coding into the script or with variables sent
from Flash. This code
print EMAIL "To: $DATA{‘recipient’}\n";
will send the e-mail to an e-mail address that Flash sent in a variable named recipient.
Note The \n escape character is used to designate a new line or carriage return. This
character is required here make sure things such as the sender and the subject
are on separate lines when the code interacts with the sendmail program on the
server. The escaped new line character (\n) should appear inside the quotation
marks of the print statement. If you’re going to include a subject, it should be the
last item, and it should be followed by two consecutive \n characters.
The body text is delivered by just using print EMAIL and either hard-coded text or a variable name in
the quotes:
print EMAIL "Dear John, very nice to see you today\n";
print EMAIL "I hope you are feeling better\n";
print EMAIL "Mark";
or
Print EMAIL "$DATA{‘message’}";
# Prints a variable from Flash named "message"
# as the body of the e-mail
First, you’ll set up an e-mail script on the server to receive the variables from Flash and create and send
an e-mail:
1.Open the CD-ROM Perl script file emailtemplate.pl This file is nearly identical to
perltemplate2.pl except for the addition of the e-mail–sending section at the end.
2.Replace the commented code section in the e-mail section of the script with the
following print statements:
3. print EMAIL "To: $DATA{‘recipient’}\n";
4. print EMAIL "From: $DATA{‘sender’}\n";
print EMAIL "$DATA{‘message’}";
Make sure to leave the open and close e-mail statements above and below the commented
code block you’re replacing.
5.Save this file on your hard drive as quickemail.pl (this file is available on the CD-
ROM if you have any problems).
6.Upload this file to your server cgi-bin folder and configure it with CHMOD 755.
This Perl script is now configured to use three variables from Flash named recipient, sender, and
message. Next, you must configure the Flash movie:
page 77
Server-Side Flash: Scripts, Databases, and Dynamic Development
1.Create a new file in Flash and save it as quickemail.fla (or just pop open the CD-
ROM file quickemail.fla, reference your Web domain in the button code, and skip to
step 11).
2.Add a stop() action to the first frame.
3.Create three input text fields on the stage.
4.Assign the variable names recipient, sender, and message to the text fields. The
sender and recipient fields can be single line and should support enough
characters to contain an e-mail address. The message field should be multiline
with word wrap.
5.Use static text fields to provide the proper labels next to the dynamic entry fields.
6.Create a button on the stage or use one from the standard Flash button library and
use a standard text field to label it Send Now!
7.Attach a loadVariablesNum statement to this button specifying the
quickemail.pl file on your server as the URL, a method of POST, and a level of
0.
8.Below the loadVariablesNum statement, add a gotoAndPlay(10) statement.
9.Create a blank frame around Frame 10 and then fill it with a static text field containing
the text “Your message has been sent!” Put 10 standard frames out in front of it.
Figure 2-8 shows the layout of the stage and timeline.
Figure 2-8: Stage layout and timeline setup for CD-ROM file quickemail.fla.
10. Preview the movie in your Web browser.
11. Enter an e-mail address in the Recipient field (preferably your own so you can test
the program) and then enter any valid e-mail address in the Sender field and any
text in the Message text box.
12. Click the Send Now! button and check your e-mail in a minute or so (some servers
can take up to 10 minutes or more if they’re slow). You should receive the exact
page 78
Server-Side Flash: Scripts, Databases, and Dynamic Development
contents of the message field sent from whatever address you entered in the
Sender field.
Perl compiles and sends an e-mail according to the three variables sent from Flash, one each for
sender, recipient, and the message body. Perl opens the sendmail program and provides the data, at
which point the server compiles and sends the e-mail. Although this script lets anyone using this Flash
movie send an e-mail to anyone else, what you probably will want to use it for most of the time is as a
standard form-processing application.
First you’ll set up an e-mail script on the server to receive the variables from Flash and create and send
an e-mail:
1.Open the CD-ROM Perl script file emailtemplate.pl.
2.Replace the commented code section marked for replacement in the e-mail section of
the script with the following print statements:
3. print EMAIL "To: $DATA{‘recipient’}\n";
4. print EMAIL "From: $DATA{‘senderemail’}\n";
5. print EMAIL "Subject: $DATA{‘subject’}\n\n";
6. foreach $i (keys %DATA) {
7. print EMAIL "$i: $DATA{$i}\n\n";
}
Make sure to leave the open and close e-mail statements above and below the commented
code block you’re replacing. This new code sends the Perl-generated e-mail to a variable
named recipient defined in Flash and makes it appear to come from whatever e-mail
address is defined in a variable in Flash named senderemail. The subject is also defined
in Flash and used here as well. The foreach statement then references the keys in the
%DATA array, which are all the variable names sent from Flash. Each one it finds is printed
into the body of the e-mail followed by a colon (:) and then its value.
8.Save this file on your hard drive as flashform.pl (this file is available on the CD-
ROM if you have any problems).
9.Upload flashform.pl to your server cgi-bin folder and configure it with CHMOD
755.
page 79
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 2-9: The stage layout for a simple Flash form that will deliver its contents to a Webmaster
using Perl to put all the data in an e-mail.
7.Select the button at the bottom of the stage and view its attached ActionScript.
Change the URL to reflect your domain and the Perl script flashform.pl that
you uploaded.
8.Immediately before that loadVariablesNum statement, enter the following lines of
ActionScript:
9. recipient="your email address";
10. subject="Result from Flash Form!!";
11. Replace the text inside the quotes of the recipient variable with your e-mail
address. If you were developing this application for a client, you would enter the e-
mail address of the person who is to receive the form results here.
12. Publish and preview this movie inside your Web browser and fill in the appropriate
text fields with whatever data you’d like. Then click the Send Now! button.
13. Wait a few minutes and check your e-mail. All of the form data should have arrived.
14. Save your new Flash movie as flashform.fla. If you’re having any problems,
the movie is available on the CD-ROM in its completed state.
The button code in Flash in this example sets the recipient of the e-mail and the subject right before it
executes the call to the Perl script. This means that people using this Flash movie can enter any data
they want, but they can send it only to the address specified in the recipient variable in the button
code!
The other great thing about the Perl script flashform.pl is that it’s modular and can support any
number of variables sent from Flash, because it’s using the foreach statement to reference them all.
Try it out:
1.Add as many other dynamic text fields as you’d like to the Flash movie you just
created.
2.Make sure each one has a unique variable name and label each text field with some
plain text for reference.
page 80
Server-Side Flash: Scripts, Databases, and Dynamic Development
3.Click the Send Now! button and watch all your variables get delivered right to your e-
mail box, courtesy of Flash and Perl.
Tip You can easily take all the elements on the stage (the text fields and the button)
and put them into any movie clip. This movie clip can then appear on-screen when
a user clicks a button to fill in the form. Because the loadVariablesNum statement
sends every variable in the timeline that it resides in, this setup is a good idea
because it separates your e-mail form variables from any others hanging around
the main timeline of your Flash movie.
The more you learn about Perl, the more you can customize the e-mail script. You could have Perl
alphabetize the fields or remove unwanted fields from the body of the message. A simple way to
remove unwanted fields would be to list only the variables you want to see in the body of the e-mail, as
in this example:
print EMAIL "To: $DATA{‘recipient’}\n";
print EMAIL "From: $DATA{‘senderemail’}\n";
print EMAIL "Subject: $DATA{‘subject’}\n\n";
You can use Flash to improve the whole system as well. If you’re really handy with ActionScript, you
could add validation code to validate entries in any of the fields to make sure they’re actually e-mail
addresses. Another obvious addition is to add some sharp-looking graphics.
Summary
As you’ve seen throughout these examples, Flash and Perl make for a very happy couple. After you get
used to the Perl syntax and the extra code it needs to split up variables from Flash, you can operate on
those variables in any way you choose. You can pop them into text files or cookies and send e-mail
messages from Flash forms with ease. Regardless of what new technologies arise in the near future,
CGI and Perl will be present on the majority of Web hosts you find. Perl is the most common language
on the Unix/Linux servers of the world, and these servers, being less expensive to install and maintain
by hosting companies, will be the standard for years to come.
Access Databases
Active Server Pages (ASP) provide you with a primary back end server-side solution. ASP can act
either as a middleman between your browser pages and a database or provide added dynamic
interaction between your browser client and server. In either role, Flash is an excellent display platform
when compared to HTML. ASP pages give you far more options when using Flash, and you quickly see
how easily you can make the ASP-Flash 5 connection.
ASP resides on NT Servers, and we have made arrangements for a month of free hosting on HosTek’s
NT Servers (www.hostek.com). The trial hosting will enable you to learn how to use ASP with Flash 5.
Both Windows and Macintosh users can take advantage of the trial hosting service. Therefore, in
explaining how to set up the server-side scripts, a single common reference can be used.
page 81
Server-Side Flash: Scripts, Databases, and Dynamic Development
to write VBScript. However, so as not to clutter and confuse references in discussing ASP, the
assumption in this chapter is that the language in question is VBScript unless otherwise stated. In other
words, “writing an ASP page” is really writing VBScript to create an ASP page.
ASP pages run either as a mix of HTML and VBScript or VBScript alone. ASP pages can contain XML
or JavaScript as well, but in this chapter we focus on using VBScript in ASP pages. In any case, ASP is
saved in the Web server’s root directory with the asp extension. The root directory varies with the setup
of your system. If you are using your HosTek account, put your files into the root folder (directory) or a
directory within the root folder and use your domain name (or IP address if you have no domain name)
as the root. The following line calls an ASP program where the domain is your.URL.com and the ASP
program is in the root directory:
http://your.URL.com/myProgram.asp
To keep the root directory uncluttered, you may want to create additional directories for different
projects. To learn how to use Flash 5 with ASP, for example, you may want to add a directory in your
Web server root directory named FlashASP and put all your ASP programs there. With this added
directory, the preceding example changes to the following line:
http://your.URL.com/FlashASP/myProgram.asp
The addressing process is identical to that for HTML files, but you must keep in mind the relative
relationship to the Web server’s root directory.
If you are using an IP address as a root directory because you have no domain name, all you need to
do is use the IP address. If your IP address is 234.56.78.910.11, for example, your access to the ASP
page shown above is as follows:
http://234.56.78.910.11/FlashASP/myProgram.asp
Either method of addressing your ASP page follows the same slash format for any URL.
Note Because this introduction to ASP is designed to get you up and running as quickly
as possible, using Flash as the front end and ASP as the back end, we’re
covering just the essentials of ASP to help you get started using VBScript to
create ASP pages. If you decide that ASP is what you need as a server-side
language, take a look at Active Server Pages Bible by Eric Smith or Active Server
Pages For Dummies by Bill Hatfield (both by IDG Books Worldwide, Inc.) for more
information.
Use a text editor such as Notepad or WordPad (Windows) or SimpleText (Macintosh) to write your ASP
scripts. To get started, write the following script:
<%
Dim Hello
Hello="HiYa George"
Response.write Hello
%>
Caution If you use Notepad, make sure that Notepad doesn’t add a txt extension in
addition to your asp extension if you save your file as a text file (Text
Documents) with an asp extension. Place quotation marks around the name of
your file when you save it to prevent Notepad from adding an unwanted txt
extension.
page 82
Server-Side Flash: Scripts, Databases, and Dynamic Development
Save the file as hello.asp in your server root directory or subdirectory. For this example, we saved
the ASP file in a folder (directory) named FlashASP in the Web server’s root directory,
your.URL.com. To launch the program, we type the following:
http://your.URL.com/FlashASP/hello.asp
Substitute your domain name for yourURL.com and your subdirectory name for FlashASP. After you
launch the program, you should see the following in the browser window:
HiYa George
If you get an error, double-check your code and check whether you placed your script in the correct root
directory or subdirectory. If you’re using your own computer as a server and client, make sure that your
server is running and the rest of your software is in place and set up correctly.
Data display
Throughout this chapter, you see the Response.write command in use. This command works
something like a print command in Basic. The Response.write command takes the materials to the
right of the command and displays them in a Web page. Generally, the Response.write command
uses the following format:
Response.write "Display this message."
You can also use the Response.write command to display functions, as in the following example:
Response.write sqr(250)
The output shows the square root of 250, which is 15.8113883008419. Throughout the rest of this
chapter, you see the Response.write command used often, because this workhorse command is
used to send information to the user through Web pages or Flash.
Comments
As in all programming languages, comments in code help developers remember what they were doing
with the code as they were developing it. VBScript uses a single quote mark (‘) to flag a line as a
comment, as in the following example:
<%
Dim item
item=49.85
‘The item must include a 7% sales tax.
item = item + (item * .07)
Response.write item
%>
Variables
Declaring a variable in ASP is different from declaring a variable in ActionScript. In ActionScript, you
define the variable with a value, and that action takes care of both the declaration and assignment. In
ASP, you need to declare variables with the Dim keyword and then assign a value to the variable. The
following example shows how to declare a variable by using VBScript in an ASP block:
<%
Dim score
score = 50
%>
The script requires that the variable score first be declared using Dim. To declare several variables,
you can declare them by using multiple Dim keywords, as follows:
Dim Ned
Dim Mo
Dim Homer
page 83
Server-Side Flash: Scripts, Databases, and Dynamic Development
Whatever method you prefer, ASP requires a variable declaration prior to your using the variable in the
script.
Data types
A variable is not limited to a single data type in VBScript. Instead, a variable can change from one type
of data to another, not unlike in ActionScript. You can also mix different types of data in a single
variable.
The following script shows three data types entered into ASP variables: integers, doubles (floating point
numbers), and a string literal. However, to format the variables into three lines for output, you must
concatenate an HTML tag, <br>, to create a line break. The tag is placed into a variable named
lnBreak, and the lnBreak variable is placed between the Response.write statements to place
output on different lines, as in the following example:
<%
Dim wholeThing, someFractions, stringBean, lnBreak
lnBreak = "<br>"
wholeThing = 6744
someFractions=22.95
stringBean= "Eat your vegetables!"
Response.write wholeThing
Response.write lnBreak
Response.write someFractions
Response.write lnBreak
Response.write stringBean
%>
For the most part, in dealing with ASP and Flash, you format the output by placing it in the appropriate
variable or movie clip, and you don’t need to worry about formatting the output in ASP scripts. What is
viewed on-screen depends on whether you are placing the output from ASP into a variable associated
with a dynamic text field or a movie clip.
If you need to know the data type of a variable at any given moment, you can use the VarType()
function. This function returns the variable as 1 of 16 coded values. For example, in the following listing,
a variable named uniVar is first defined as a floating-point number, and the VarType() function
returns the code for a double-precision floating-point number. Then the variable uniVar is
concatenated with a string, changing the variable to a string. As a result, the code for a string is
returned.
<%
Dim uniVar, lnBreak
lnBreak="<br>"
uniVar=123.45
Response.write VarType(uniVar)
Response.write lnBreak
uniVar= uniVar & "A Word"
Response.write VarType(uniVar)
%>
page 84
Server-Side Flash: Scripts, Databases, and Dynamic Development
5
8
Those two codes are for the variable’s first incarnation as a double and then its second incarnation as a
string. Table 3-1 shows the entire list of code for the different types of data using the VarType function.
Table 3-1: VarType Codes
Operators
The VBScript operators used in ASP 3.0 are different in places from those found in Flash 5 ActionScript,
but you find many similarities as well. VBScript has its origins in Microsoft Visual Basic, whereas
ActionScript has an appearance and structure more like that of JavaScript. Remember also that the
page 85
Server-Side Flash: Scripts, Databases, and Dynamic Development
VBScript in ASP 3.0 was not written with Flash in mind, while ActionScript very much was. (In other
words, don’t expect to find a gotoAndPlay() statement in VBScript.) Table 3-2 shows the VBScript
operators used in ASP.
Table 3-2: ASP Operators
Conditional statements
The conditional statements in both ActionScript and VBScript accomplish similar goals, but they are
written differently. If you are familiar with just about any version of Basic, especially Microsoft Visual
Basic, you are on very familiar ground with VBScript. If, however, your scripting background is more on
the lines of JavaScript and ActionScript, pay close attention to the differences.
page 86
Server-Side Flash: Scripts, Databases, and Dynamic Development
oranges=20
if apples <> oranges then Response.write "I didn’t think so."
%>
If you have an alternative to the conditional statement using else, the else clause is initiated
automatically if the if condition is not met. The following script shows how else works:
<%
Dim suzy, ralph
suzy="smart"
ralph="strong"
if (suzy="smart") And (ralph="smart") Then Response.write "Off to gifted class" Else Response.write "To
each his or her own."
%>
Notice how the logical AND operator is used in the script. And the line beginning with if does not end
until own. Both the then and else statements are part of the same line. To make the code clearer,
you can use an underscore (_) as a continuation character. For example, you can add underscores to
the preceding listing to make it clearer, as the following example shows:
<%
Dim suzy, ralph
suzy="smart"
ralph="strong"
if (suzy="smart") And (ralph="smart") _
Then _
Response.write "Off to gifted class" _
Else _
Response.write "To each his or her own."
%>
Either way works, but some people find the underscores to be distracting. If you do use the underscores
as a continuation character in your scripts, make sure that you put a space between the underscore and
the previous character in the line.
You can use the ElseIf keyword if you have several different conditions to list, as in the following
example:
If A=1 Then do this
ElseIf A=2 Then do that
ElseIf A3 Then go home
Else Give up and go back to work
End If
page 87
Server-Side Flash: Scripts, Databases, and Dynamic Development
End Select
The Select Case structure makes scripting several conditions much clearer, and the Case Else
statement provides an automatic alternative for none of the conditions being met. The End Select
statement acts as a terminator for the structure.
The following example shows how Select Case might be used. In an application, the contents of the
variable would be provided by a user visiting an e-commerce site rather than defined in the script.
<%
Dim product
product="Laptop"
Select Case product
Case "Desktop" Response.write "We have PCs and Macs."
Case "Laptop" Response.write "Several brands of laptops are available."
Case "Software" Response.write "We have utilities, applications, and games."
Case Else Response.write "We do not carry that product or service."
End Select
%>
ActionScript does not have an equivalent to the Select Case statement, but passing data between an
ASP Select Case statement and Flash is simply a matter of formatting any outcome from a Select
Case structure to be read by Flash 5 ActionScript. We examine how to do that in the next section.
Conditional statements are important for server-side scripts because such statements are the decision-
makers. If you create a dynamic site, the data from the Flash 5 front-end often must be analyzed in an
ASP script, so seeing the similarities and differences between formatting conditional statements in
ActionScript and formatting them in ASP is important.
Loops
ASP has two basic loop structures: For...Next and Do.... You find some similarities between
ActionScript loops and those in VBScript, but VBScript loops are formatted more along the lines of Basic
than either ActionScript or JavaScript.
Do loop structures
VBScript provides a number of variations on the Do loop. Depending on what you need from a loop and
your programming style, each has a slightly different function and format.
Do...While loop
At the beginning of the Do...While loop, a statement specifies the conditions under which the loop
terminates. All loop actions take place between the defining conditions of the loop and the Loop
statement that terminates the loop, as follows:
<%
Dim counter, lnBreak
lnBreak="<br>"
counter=1
Do While counter <=5
Response.write ( "Loop" & " " & counter)
Response.write lnBreak
counter = counter + 1
Loop
%>
Do...Until loop
About the only difference between the Do...While loop and the Do...Until loop is that the former
guarantees at least one pass through the loop even if the termination condition matches the counter
variable value. As soon as the Do...Until loop encounters the termination condition, it exits the loop
page 88
Server-Side Flash: Scripts, Databases, and Dynamic Development
without executing the statements in the loop. Compare the Do...While loop example with the
following to see the differences:
<%
Dim counter, lnBreak
lnBreak="<br>"
counter=1
Do Until counter =5
Response.write ( "Loop" & " " & counter)
Response.write lnBreak
counter = counter + 1
Loop
%>
Step feature
A nice feature of VBScript For...Next loops is the Step keyword. Using Step, you can make the
loop increments in a number of positive or negative steps. The following script illustrates this feature:
<%
Dim counter, lnBreak
lnBreak="<br>"
For counter = 20 to 1 Step -4
Response.write ( "Loop" & " " & counter)
Response.write lnBreak
Next
%>
Arrays
Arrays in ASP and ActionScript differ in several ways, but the concepts are identical. Arrays are
especially important in ASP for organizing database information. VBScript has a number of different
ways to create an array in ASP. First, you can just use an array name and assign literal values to each
element in the array. As with variables, you must first establish a dimension for the array. For example,
the following is a simple array in ASP:
page 89
Server-Side Flash: Scripts, Databases, and Dynamic Development
<%
Dim item(4)
item(0) = "monitor"
item(1) = "keyboard"
item(2) = "motherboard"
item(3) = "mouse"
Response.write item(2)
%>
Like arrays in other scripting and programming languages, the initial element is the zero (0) element,
and not one (1). Also notice that, in VBScript, the array elements are in parentheses and not in brackets
as in ActionScript.
Multidimensional arrays
Especially if you work with databases, one of the nice features of VBScript’s arrays is the ease with
which you can declare them to more than a single dimension. Suppose that you have a service
database that contains all the different service costs a company has. Each record is a client, and each
field is a different service cost. To arrange the data from that database, you can place it in a two-
dimensional array. The first element is the client, and the second is the service cost. The company has
five different services and 300 clients, so the array can be dimensioned as follows:
Dim arrService (300,5)
Or consider it as follows:
Dim arrService (Client,Service Cost)
If you want to look at output showing what a particular client is billed broken down by service cost, you
can write a script that looks at the client’s name associated with the value of the first dimension and a
service cost associated with the value of the second dimension. The following script shows how the
parts of the two-dimensional array work with a client with the ID number of 259:
<%
Dim arrService(300,5), lnBreak
lnBreak="<br>"
arrService(259,0)=345.95
arrService(259,1)=0
arrService(259,2)=1342.87
arrService(259,3)=904.22
arrService(259,4)=0
Response.write ("Artwork = " & "$" & ArrService(259,0))
Response.write lnBreak
Response.write ("Consulting = " & "$" & ArrService(259,1))
Response.write lnBreak
Response.write ("Flash = " & "$" & ArrService(259,2))
Response.write lnBreak
Response.write ("Design = " & "$" & ArrService(259,3))
Response.write lnBreak
Response.write ("Hosting = " & "$" & ArrService(259,4))
%>
page 90
Server-Side Flash: Scripts, Databases, and Dynamic Development
The output looks like what you see in the following example:
Artwork=$345.95
Consulting=$0
Flash=$1342.87
Design=$904.22
Hosting=$0
With this structure, you don’t need 300 different scripts to get through 300 records.
Functions
As does ActionScript, VBScript has both built-in functions and user functions. For example, the
VarType() function, used previously in this chapter, is built into VBScript. Similarly, a number of other
functions are built into VBScript, but only a small subset of these that can be used with Flash 5 are
going to be discussed in this book. (See VBScript Language Reference at
http://msdn.microsoft.com/scripting/default.htm?/scripting/vbscript for a full
listing of functions in VBScript, along with detailed explanations.) User functions in both ActionScript and
VBScript are similar in structure and application. A user function is defined with a word using optional
arguments and then a list of statements and is terminated with an End Function statement. For
example, a function to add tax and shipping to an item can be written as follows:
<%
Function taxShip(item)
taxShip = item + (item *.07) +4.95
End Function
Response.write taxShip(19.95)
%>
The trick is, of course, to get the input from Flash 5 and use the data to do something. Eventually, you
want to use ASP to take Flash 5 data and put it into a data file and pull data out of a file and output it in
a Flash 5 movie.
page 91
Server-Side Flash: Scripts, Databases, and Dynamic Development
Optionally, you can place an ampersand before the initial variable name. Some developers like to place
an ampersand before the first variable to ensure that all the variables contain a leading ampersand and
are, therefore, easier to identify.
Color palette
All color palettes come from a set of color combinations that compliment one another and help improve
the general appearance of the movie. You add each color by first using the values (hexadecimal) for
each color in the Mixer panel and then selecting Add Swatch from the pop-up menu in the Mixer panel’s
upper right corner. To create the color palette for ASP2Flash.fla, you need to add three colors, Red,
Green, and Blue, with the values specified in the following table.
Labels layer
Follow this next set of steps to create the background color and elements for the layer:
1. The background color is set to yellow. Choose Modify → Movie and select Color
C from the movie’s color palette.
page 92
Server-Side Flash: Scripts, Databases, and Dynamic Development
2. Draw a red rectangle using Color A for fill and stroke. Make the rectangle roughly
W=150, H=30. Use Color B and a bold 12-point Verdana font to write the label
From ASP to Flash on top of the rectangle.
3. Draw a green rectangle using Color B for fill and stroke. Set the rectangle
dimensions to W=230, H =36.
4. Use as 12-point red Verdana font and type Click Button to the left of the bottom
rectangle. Leave room between the label and the green rectangle for a button.
See Figure 3-1 to see the placement of the different objects on the stage. Lock
the layer after you finish.
Figure 3-1: The stage area contains a single text field and a button for the ActionScript.
Button layer
The button holds the ActionScript that loads the variables from ASP. The following set of steps shows
how to set it up:
page 93
Server-Side Flash: Scripts, Databases, and Dynamic Development
1. Use the Oval tool to draw a circle, using Color A for the fill and black for the
stroke.
2. Select the circle and text and press the F8 key to open the Symbol Properties
dialog box. Select Button for the Behavior and, in the Name window, type
ASPgetter. Click OK to create a button symbol.
3. Select the button instance and click the Action panel icon (arrow) on the
launcher bar to open the Objects Action panel. Enter the following script,
substituting the URL with the one you use as your root directory and subdirectory
in your root directory:
4. on (release) {
5. loadVariablesNum
6. ("http://your.URL.com/FlashASP/flash1.asp", 0);
}
While entering the ActionScript in the Normal mode, place the parameter values as shown in
Figure 3-2. Use the default Level value of 0, and type the URL in the URL window. You do
not want to send any variables to ASP, so leave the Variable pop-up menu in the default
state of “Don’t send.”
Figure 3-2: In the Normal mode, the parameter values are placed at the bottom of the
ActionScript editor.
page 94
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-3: The text field associated with the variable name displays the contents from the server-side
script.
The general format for sending data from Flash to a server script is as follows:
loadVariablesNum ("http://your.URL.com/ASP/grand.asp", 0, "POST")
The format looks identical to the format for loading variables into Flash, except that "POST" is added
after the level value.
Which variables are sent from Flash? All variables are sent. However, each one must be captured in
ASP separately. The VBScript Request.Form() function works great with Flash forms. All you need to
do is to place the name of the Flash variable you’re sending into a VBScript variable using the
Request.Form() function. Suppose that two variables, item and price, are sent from Flash to an
ASP page. To retrieve those two variables and place them into ASP variables, you use the following
script:
<%
dim item, price
item=Request.Form("item")
price=Request.Form("price")
%>
After the data passes from Flash to variables in an ASP page, the data can be used for further
calculations, for formatting, or passed to a database.
page 95
Server-Side Flash: Scripts, Databases, and Dynamic Development
Color palette
Use the color palette in Table 3-3 for the movie. Use Color F for the background color.
Table 3-3: Color Palette for Flash2ASPnBack.fla
Background layer
Begin with the bottom layer. By placing all the labels and backdrops for the movie, you can get a better
feel of where everything else goes. Just follow these steps:
1. Choose Modify → Movie and, in the Background Color well, select Color F
(yellow) for the background.
2. In the middle of the stage near the top, draw two backdrops using the Rectangle
tool. Use Color A for both the fill and stroke colors and give each rectangle the
dimensions W=134, H=32.
3. To the right of the top backdrop, type Input using a bold 12-point Verdana font in
Color D. Using the same font and color, type Output to the right of the bottom
backdrop. (See Figure 3-4 to give you a clear idea of what this looks like.)
4. To the left of the two rectangles, type a Click Button label using a 12-point
Verdana font in Color C, as shown in Figure 3-4. Leave space for the button that
goes between the label and the text field backdrops.
5. Lock the layer.
page 96
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-4: Two text fields provide an entry portal (input) and return data window from the
ASP page (output); a button contains the ActionScript to launch the process.
2. Open the Text Options panel and select Input Text from the top pop-up menu.
Check the Border/Bg box.
3. In the Variable box on the Text Options panel, type input for the variable name
to be associated with the text field.
4. Repeat steps 1, 2, and 3, except select Dynamic Text as the type of text field
and deselect the Border/Bg box. Use the name output for the variable name in
the Text Options panel.
Button layer
The button holds the ActionScript that loads the variables from ASP. The following set of steps shows
how to set it up:
1. Use the Oval tool to draw a circle using Color B for the fill and Color D for the
stroke.
2. Select the circle and press the F8 key to open the Symbol Properties dialog box.
Select Button for the Behavior and, in the Name box, type InAndOut. Click OK
to create a button symbol.
3. Select the button instance and click the Action panel icon (arrow) on the
launcher bar to open the Objects Actions panel. Enter the following script,
substituting your own path:
4. on (release) {
5. loadVariablesNum
6. ("http://your.URL.com/FlashASP/flashback.asp",
7. 0, "POST");
}
8. In the Object Actions panel, type the URL in the URL box. Use the default Level
value of 0. In the Variables drop-down list box, select Send using POST. These
parameter values are as shown in Figure 3-5.
page 97
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-5: All variables in the Flash movie are sent using Send using POST.
page 98
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-6: The input from Flash is modified in ASP and returned as output in Flash.
The next step is to see how data gathered in a Flash front end can be used in calculations generated by
ASP. The calculations can be simple or complex, and most can be accomplished by client-side scripts
in ActionScript. But seeing how to pass calculated data from a ASP script with data originating in Flash
is the first step in using wholly ASP-generated data for output in Flash.
Color palette
Use the color palette in Table 3-4 for the movie. Use Color B (deep red/brown) for the background color.
Set Color D as black and Color E as white.
page 99
Server-Side Flash: Scripts, Databases, and Dynamic Development
Input layer
Like the last movie, the input field is used to provide data associated with a variable that will be sent to
the ASP script on the server. The following set of steps covers the process for creating the input text
field:
1. Select the Text tool and draw a rectangle text field near the top of the stage, as
shown in Figure 3-7.
Figure 3-7: The first text field is used to input data that is sent to the ASP script, calculated, and
then returned to Flash in the output window.
2. Open the Text Options panel and select Input Text from the top pop-up menu. In
the Variable box, type input for the variable name to be associated with the text
field.
3. In the Character panel, select Verdana as the type and black for the text color.
4. Using Color C and a bold Verdana 12-point font, type Enter item price:, as
shown in Figure 3-7.
Button layer
The ActionScript in the button sends data to VBScript script, but it does no calculation itself. The script
is almost identical to the previous Flash movie, but the button is a little different; follow these steps:
1. Use the Oval tool to draw an oval using Color A for the fill and white for the
stroke. Type Total on top of the oval.
page 100
Server-Side Flash: Scripts, Databases, and Dynamic Development
2. Select the oval and the text on the oval and press the F8 key to open the Symbol
Properties dialog box. Select Button for the Behavior and, in the Name box, type
calcToASP. Click OK to create a button symbol.
3. Select the button instance and click the Action panel icon (arrow) on the
launcher bar to open the Object Actions panel. Enter the following script,
substituting your own path:
4. on (release) {
5. loadVariablesNum
6. ("http://your.URL.com/FlashASP/dataBack.asp",
7. 0, "POST");
}
8. Type the URL in the URL box and use the default Level value of 0. In the
Variables drop-down list, select Send using POST.
Output layer
The Output text field goes below the button (refer to Figure 3-7). Follow the steps for the Input layer
except select Dynamic Text from the pop-up menu in the Text Options panel and type output for the
variable name to associate with the field.
page 101
Server-Side Flash: Scripts, Databases, and Dynamic Development
The function name and arguments are standard, as are the calculations and formatting statements.
However, after all the formatting is completed and stored in ASP variables, the Flash variables must be
formatted to read the ASP variables within the function’s parameters. For example, the following
function is another tax and shipping one with the Flash formatting added. After the function is called
from Flash, it returns the input value from Flash with the tax and shipping added.
<%
Function taxShip(item)
taxShip = item + (item *.07) +4.95
End Function
Dim results, output
results=taxShip(Request.Form("input"))
output="output=" & "$" & results
Response.write output
%>
Save the ASP file as taxShipFlashFunction.asp and save it in your root directory on the server.
Then, using the movie from the previous example (ASPCalc.fla), change the button script to read as
follows:
on (release) {
loadVariablesNum
("http://your.URL.com/FlashASP
/taxShipFlashFunction.asp", 0, "POST");
}
Try out the movie by pressing Ctrl+Enter (in Windows) or Cmd+Return (on the Macintosh). After the
SWF file appears, type a value and click the button. You should see the value you entered returned with
tax and shipping costs added, as shown in Figure 3-8.
page 102
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-8: All the calculations in the Total cost are generated in a VBScript function on an ASP page and
returned to Flash for output.
Data from a database can be placed into an array for transfer to and from Flash and ASP. In looking at
how arrays behave, you quickly see that they are treated no differently than variables. The great
advantage of an array, though, is that a series of numbers can be used to access the array, and by
understanding how to use array elements and associated values, you can better establish a way to
organize and pass data between Flash and ASP.
On the Flash side, the arrays can be associated with text fields for displaying any or all elements of the
array. On the ASP side, the array elements can be coordinated to the text fields. In this way, whatever
value is passed from Flash to ASP can be used to coordinate ASP data and Flash output.
page 103
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-9: Each of the text fields is associated with an array element.
Color palette
The movie uses a simple gray, purple, black, and white color palette whose values are shown in Table
3-5. Color C is black, and Color D is white.
Table 3-5: Color Palette for ASParray.fla
Background layer
Follow these steps to create the Background layer:
1. Choose Modify → Movie and then select the color palette’s purple color (Color
A) for the background.
2. Draw a gray rectangle with black strokes to serve as a backdrop to a text field.
Use the Info panel to set the rectangle dimensions to W=259 and H=28.
3. Select the rectangle and then choose Modify → Group so that the stroke and fill
are grouped.
4. Make four identical copies of the rectangle and line them up vertically using the
Align panel to space and align them (see Figure 3-10).
Buttons layer
Create five buttons and label them from 1 to 5, as shown in Figure 3-10. These buttons contain scripts
that send data to the ASP script and fire the ASP script. The value of the variable myData is the array
element value of the text field adjacent to the button. In the ASP script, you see how that value is used
page 104
Server-Side Flash: Scripts, Databases, and Dynamic Development
to return the correct message after the button is clicked. Substitute your URL for the one provided in the
following example:
on (release) {
myData = 1;
loadVariablesNum
("http://your.URL.com/FlashASP/arrayData.asp", 0,
"POST");
}
Create a sixth button and label it Reset. The Reset button launches an ASP script that places a space in
each of the five text fields, effectively resetting them all:
on (release) {
loadVariablesNum
("http://your.URL.com/ASP/clearArray.asp", 0)
}
page 105
Server-Side Flash: Scripts, Databases, and Dynamic Development
flashData=Request.form("myData")
output = "out[" & flashData & "]=" & item(flashData)
Response.write output
%>
The second ASP script clears out all of the text fields by placing a space in the field. In the following
script, make sure that you put a space between the equal sign (=) and the ampersand (&). Save the
script in the server’s root directory or a subdirectory in the root directory under the name "
clearArray.asp.
<%
Dim output
output = "out[1]= &out[2]= &out[3]= &out[4]= &out[5]= &"
Response.Write output
%>
Figure 3-10 shows the SWF file where three of the buttons are clicked.
Figure 3-10: Arrays written in ASP can connect with an array in ActionScript.
page 106
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-11: Three different files are involved in sending data between Flash 5 and a database.
Placing the Access 2000 file on the server and preparing the DSN
The next step is to open the root folder where you have been placing your ASP pages and place your
database file there. If you are using a remote server, just use FTP to move the Access 2000 file to the
root folder or subfolder on the NT Server.
Next, you need to create a data source name (DSN) connection to the database on the server. This
connection enables your ASP application to interact with the database. After you enter the database
filename in an ASP script, the server software uses the DSN name to enable a connection.
page 107
Server-Side Flash: Scripts, Databases, and Dynamic Development
For Windows 2000 and Windows NT, use the following steps:
1. Choose Start → Settings → Control Panel. In the Control Panel, double-click the
ODBC Data Sources icon to open the ODBC Data Source Administrator.
2. Click the File DSN tab, click Add, and then select Microsoft Access Driver (*mdb)
from the menu and click Next.
3. Type a descriptive name. We used EmailFlash for the file DSN name. Click Next.
4. Click Finish and then click Select. Navigate to the directory of your database file; it
appears in the left window under Database Name. Click your database (for example,
emailFlash.mdb) to select it and then click OK.
5. Click OK twice. In the ODBC Data Source Administrator window in the File DSN tab,
you see your new DSN name with the extension dsn added.
This next set of steps requires that you know the path in your server that is used to make the connection
to your database file. On the face of it, the process is quite simple, but in practice, the process can be
quite confusing. After you get the formula, however, you can reuse it on any database within the same
server. For example, two different servers we used in developing the material for this book had different
internal paths to the data. The HosTek hosting service provided one server. The HosTek paths look
something like the following example:
d:\home\hnt1a234\ASPbase\emailFlash.mdb;
A different server used the following path, which is probably very similar to what those who use their
own computers as servers and clients use:
d:\Inetpub\Wwwroot\ASPbase\emailFlash.mdb;
The fact that both servers use Drive D is coincidental and not a requirement. They could just as well
have used Drive C or E or any other drive. The important fact to notice in both the paths is that they are
internal paths to the root directories. Although a different address needed to be used to access the ASP
pages (for example, http://your.URL.com) that contained the code, the path in the ASP page
referenced a local, internal path for the server.
The path is just part of a longer driver definition required to connect the ASP script to the database and
the data within it. Generally, the path is defined in a variable, and then the VBScript uses that variable in
other commands to make the connection. First, the provider needs to be defined. The following line
defines the driver in the variable named Serv:
Serv= "Driver={Microsoft Access Driver (*.mdb)};
DBQ=d:\Inetpub\Wwwroot\ASPbase\emailFlash.mdb;"
Because the provider information has been placed into a variable, you can use only the variable name
instead of the long line of code if the provider must be used.
The rudiments of setting up an ASP page to make a connection to a database and pull out data to be
sent to Flash can best be seen in a complete page and example. In that way, you can better understand
the context of the required code. The following Flash 5 movie and ASP page pull together the different
parts needed to see the contents of a database on a server.
Conn.Open Serv
page 108
Server-Side Flash: Scripts, Databases, and Dynamic Development
RecordView.Close
Conn.Close
Set RecordView = Nothing
Set Conn = Nothing
%>
The script is divided into five blocks. Each block is considered separately. The first block is for
dimensioning the variables, defining the connections, and then setting the connections. Several
variables are defined using the Dim statement. Next, the driver and provider are placed into the Serv
variable. The ADODB connection object is placed into the Conn variable, and the ADODB recordset
object is placed in a variable named RecordView.
On the CD- All the files that are used in the examples in this and the following sections
ROM are available on the CD-ROM.
The second block opens the connection and defines an SQL command. (The variable name SQL is
used to emphasize the fact that the variable contains an SQL command, but you could use any variable
name you want.) The command (or action query) selects all the records (* = wildcard) from the table
named EmailTable in the Access 2000 file named emailFlash.mdb. The next line opens up the
recordset in the database defined in the connection and issues the SQL command.
A loop dominates the third block. One of the nicer features of VBScript is that it can loop through a
recordset until it encounters the EOF (end of file) of the recordset. Another feature to note in this block is
the use of the <BR> tag. Used in HTML as a line break, this tag works just as well as a line break in a
Flash 5 text field. The collect variable concatenates the data with the line break tag through the
entire loop. To keep this first example simple, only one of the three fields, Name, is passed to a variable
that is sent to Flash.
The fourth block transforms the accumulated variable, collect, into a format that can be read as a
variable by Flash. Although the output variable is not declared in the VBScript, the variable is
recognized as a Flash variable because of the = sign attached to it. Finally, the last block of code closes
up the connection and recordset and resets the variables.
page 109
Server-Side Flash: Scripts, Databases, and Dynamic Development
Background layer
Use Color A as the background color. Draw a rectangle with the Rectangle tool, using Color B as the fill
color and Color D as the stroke to create a backdrop for the text field. The rectangle should have these
dimensions: W=200, H=166. Using Figure 3-12 as a guide, type Click to view data to the left of the
rectangle.
Figure 3-12: The text field dominates the stage because it is where all the data is sent.
page 110
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
Test the program and, depending on what names you put into the database, you see something like the
example shown in Figure 3-13.
Figure 3-13: The formatting of the names in the Flash text field is accomplished through the <BR> tag
added to each name from the database in the ASP page.
Conn.Open Serv
SQL="SELECT * FROM EmailTable"
RecordView.Open SQL, Conn
page 111
Server-Side Flash: Scripts, Databases, and Dynamic Development
RecordView.MoveNext
Loop
RecordView.Close
Conn.Close
Set RecordView = Nothing
Set Conn = Nothing
%>
The new variable, Email, examines the recordset of the field in the database with the same name. Both
it and the other variable are formatted into a variable named collect and then gathered up into an
output variable and sent back to Flash with the Response.Write statement. The Flash movie
requires a wider text field and the button moved out of the way, but otherwise, it is identical to the first
one. A different color palette, provided in Table 3-7, helps to distinguish this movie from the first movie.
Use the same layers, as shown in the following list:
Background
Text Field
Action Button
Table 3-7: Color Palette for Access2FlashAll.fla
Background layer
Use Color B for the background color. Draw a rectangle with Color A for the fill and Color C for the
stroke in the dimensions W=450, H-166. Then enter a Click Button label near the top and a Name ->
Email address label near the bottom, using Figure 3-14 to judge placement.
page 112
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-14: Using simple formatting and a single output window, Flash can display multiple fields from a
database.
Both lines are in a middle of a loop that reads records from the database until the database runs out of
data. The first time through the loop, the script has the following literal values:
Ename(0)=RecordView("Name")
...
output(0)="&output["& 0 & "]=" & Ename(0)
...
The first line puts the first record of the Name file into the array element Ename(0). After the program
reaches the output array element, it is in the first round of the loop, so the output element is
output(0). The results are concatenated, so the contents of output(0) are as follows:
page 113
Server-Side Flash: Scripts, Databases, and Dynamic Development
&output[0]=DBname1
After the program reaches Response.Write output(Counter) for the first time, Flash receives the
first concatenated results. Flash treats the ampersand as a variable demarcation and places the value
of the first database name into the array element output[0].
Note VBScript uses parentheses (x) to enclose the element value of an array while
ActionScirpt uses brackets [x]. So in addition to translating the data into Flash
format, you must also translate the array elements into the ActionScript format.
The second time through the loop, the concatenated value is as follows:
&output[1]=DBname2
Because the text begins with an ampersand, Flash treats it as another new variable or, in this case, a
new array element. Without the leading ampersand, Flash would assume that everything else was part
of the first array element. By using array names for text fields, you can place the data anywhere that you
want on the stage.
Save the following script as ArrayOutput.asp in your server’s root directory or subdirectory in the
root directory. The arrays were dimensioned for 10 elements arbitrarily; you can change that value to
the number of elements in your database.
<%
Dim Serv, Conn, RecordView, Ename(10), Email(10)
Dim Counter, output(10), eoutput(10), SQL
Serv= "Driver={Microsoft Access Driver (*.mdb)}; DBQ=d:\Inetpub\Wwwroot\ASPbase\emailFlash.mdb;"
Set Conn = Server.CreateObject("ADODB.Connection")
Set RecordView = Server.CreateObject("ADODB.Recordset")
Conn.Open Serv
SQL="SELECT * FROM EmailTable"
RecordView.Open SQL, Conn
Counter=0
Do While Not RecordView.EOF
Ename(Counter)=RecordView("Name")
Email(Counter)=RecordView("Email")
output(Counter)= "&output
[" & Counter & "]=" & _ Ename(Counter)
eoutput(Counter)= "&eoutput
[" & Counter & "]=" & _ Email(Counter)
Response.Write output(Counter)
Response.Write eoutput(Counter)
Counter=Counter +1
RecordView.MoveNext
Loop
RecordView.Close
Conn.Close
Set RecordView = Nothing
Set Conn = Nothing
%>
On the Flash 5 side of the equation, all you need to do is to provide arrays to receive the data and some
ActionScript to load the data into Flash. The movie is similar to the first two examined for bringing in the
page 114
Server-Side Flash: Scripts, Databases, and Dynamic Development
variables from ASP and the Access 2000 database, except that more fields are used and array
elements are used instead of variables in the text fields. The movie uses the following three layers and
the color palette in Table 3-8:
Background
Action Button
Text Fields
Table 3-8: Color Palette for AccessArray.fla
Figure 3-15: Each of the six text fields is associated with a different array element.
Background layer
The Background layer contains the rectangular backdrops for the text fields and labels. Complete these
steps to create the Background layer:
1. Use Color C for the background color.
2. Draw two rectangles with Color D as the fill and Color A as the stroke, using
Figure 3-15 as a guide.
3. In the top, smaller rectangle, type the label Name and Email Address using
Color E for the text color and a bold Verdana font.
page 115
Server-Side Flash: Scripts, Databases, and Dynamic Development
4. Below where the button is placed, type Click to display database, using Color
B for the text color.
5. Lock the layer.
Position the button to the left of the larger of the two rectangles on the background layer.
page 116
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-16: Spacing and alignment can be more precisely controlled if output is placed into individual text
fields.
The last step in this introduction to using Flash with ASP and Microsoft Access 2000 is to see how to
insert records into an Access database from Flash. When inserting records into an Access database,
you must insert data into all fields, or you generate an error. In the example used of a three-field
database that has an automatic numbering system for the ID field and text for both the Name and Email
fields, the procedure is relatively simple.
As you’re adding, deleting, and modifying records in Access from your desktop, you can use all the tools
provided with Access to make the job fairly simple. However, in adding data to a remote Access file, you
need to build an ASP page to handle the data coming from Flash and writing to the data file. Included in
this page is a script to automatically increment the ID field and a way to check to make sure that your
record is indeed in the database.
To show how everything works, we chose to generate three small ASP files instead of creating a big
ASP file and launch the scripts using three buttons in the Flash movie. One ASP script finds the value of
the highest ID number, adds one to it, and uses that value as the next number in the automatic
numbering of the ID field. A second ASP page takes input from Flash and writes to the three data fields.
Finally, a third ASP page rummages through the database and checks whether the file you just entered
is there and prints it on-screen for you.
To provide a context for inserting records into an Access file on a server with Flash and ASP, we begin
with the Flash movie. The movie contains three buttons, each to launch a different ASP script. In
addition, the movie has four text fields, one each for the three fields in the database and one to return
the most recently entered record. Figure 3-17 shows the initial stage for the movie.
page 117
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 3-17: Several buttons launch different ASP scripts to either get information from the database or add
records to it.
The movie’s color palette is in Table 3-9, and the movie contains the following layers:
Background
Button
Text Fields
Table 3-9: Color Palette for AddRecords.fla
Background layer
In the background color well (choose Modify → Movie), select Color A to give the movie a rich brown
background. Using Figure 3-18 for a guide, enter the following labels:
page 118
Server-Side Flash: Scripts, Databases, and Dynamic Development
Use a 14-point bold white Verdana font to enter Click ID Button First and then add
new record.
Use Color C to type the ID, Name, and Email labels to the right of the text fields you are
placing.
Use Color B (orange) to type the button labels: ID Button, Add Record, and Verify
Record.
Button layer
Each of the three buttons is associated with an ASP page, so we first look at the ASP page and then the
button associated with it. The ID button calls an ASP page that counts the number of records in the file
and returns a value to the ID field that represents the automatic next value for the record. Save the code
for this page as GetID.asp in your root directory or a subdirectory within the root directory. Make sure
that you substitute your own server path for the one listed in the following example:
<%
Dim Serv, Conn, RecordView, output, SQL
Serv= "Driver={Microsoft Access Driver (*.mdb)}; _
DBQ=d:\Inetpub\Wwwroot\ASPbase\emailFlash.mdb;"
Set Conn = Server.CreateObject("ADODB.Connection")
Set RecordView = Server.CreateObject("ADODB.Recordset")
Conn.Open Serv
SQL="SELECT * FROM EmailTable"
RecordView.Open SQL, Conn
Counter=0
Do While Not RecordView.EOF
Counter = Counter +1
RecordView.MoveNext
Loop
RecordView.Close
Conn.Close
Set RecordView = Nothing
Set Conn = Nothing
%>
This script is very much like the initial scripts used in this chapter to examine the contents of the
database. However, all it does is cycle through the database, counting how many records are in it, and
returns the next ID number to the Flash movie’s text field associated with the variable named ID. The
ActionScript to launch the script is as follows:
on (release) {
loadVariablesNum
("http://your.URL.com/ASPbase/GetID.asp", 0);
}
page 119
Server-Side Flash: Scripts, Databases, and Dynamic Development
Objects) file. The most work is getting the format for the SQL command right, and after that’s done, the
script follows a familiar path. Save this file in your root directory as AddAccess.asp, substituting your
own server’s path for the one listed. And remember that Source=d:\Inetpub\Wwwroot.... needs
to be changed to your home path (for example, Source=d:\home\hnt1a2345...) provided by your
hosting company.
<!-- METADATA TYPE="typelib"
FILE="C:\Program Files\Common Files\System\ado\msado15.dll" -->
<HTML>
<%
Dim Conn, Cmd, intNoOfRecords, nID, nName, nEmail, SQL
nID=Request.Form("ID")
nName=Request.Form("Name")
nEmail=Request.Form("Email")
SQL= "INSERT INTO EmailTable(Id, Name,Email) VALUES (" & _ nID & ",’" & nName & "‘,’" & nEmail &
"‘)"
Cmd.CommandText =SQL
Cmd.CommandType = adCmdText
Cmd.Execute intNoOfRecords
Set Cmd = Nothing
%>
</HTML>
Once in the VBScript, the variables are dimensioned and then data from Flash are pulled into the page
using Request.Form(). The variables from Flash are ID, Name, and Email, and they are set in ASP
variables of the same name preceded by the small letter n. Next the connection protocols establish a
link with the database. (If you are using Access 97, substitute 4.0 with 3.1 right after OLEDB.)
When using the SQL command INSERT INTO, you must list the names of each field, and then insert
data into them. After VALUES, placing literals into the table would look like the following example:
"...VALUES (15, ‘Suzy Smith’, ‘[email protected]’)"
Because you need to use variables instead of numeric and text literals, the variables must be
concatenated into the format recognized by VBScript. Only the variables themselves need not be in
quotation marks, and all other text must have single quote marks around it. When copying the SQL
contents, be very careful. (Remember that the underscore at the end of the SQL assignment line simply
means that the line is extended. In your text editor, you can place it all on one line and leave out the
underscore.)
The script associated with the Flash 5 button symbol for adding a record is just a little different from
most of the ActionScript in this chapter, as the following example shows:
on (release) {
loadVariablesNum
("http://your.URL.com/ASPbase/AddAccess.asp",
0, "POST");
page 120
Server-Side Flash: Scripts, Databases, and Dynamic Development
name="sent to database"
email="sent to database"
}
The button script starts off like most of the others in this chapter except that it does POST the variables.
After that information is sent, you can change the values of the variables associated with the text fields
where data is to be entered. By changing the values, you enable the user to see that something has
happened to the data he or she just entered. So after the name and e-mail data are sent, the sent to
database message appears and gives the user some feedback.
The ASP page for the Verify Record button simply loads the last record from the database into the page
so that the user is certain the data is correctly stored. This is accomplished by going through all the
records using an array and loading the last array element. The array is set to 100, but you can make it
larger or smaller by changing the array limits in the Dim statement line. Save the file in the root directory
as VerifyRecord.asp and make sure that you change the path in the following example to the one
that your server is using:
<%
Dim Serv, Conn, RecordView, Ename(100), Email(100), output
Serv= "Driver={Microsoft Access Driver (*.mdb)}; _
DBQ=d:\Inetpub\Wwwroot\ASPbase\emailFlash.mdb;"
Set Conn = Server.CreateObject("ADODB.Connection")
Set RecordView = Server.CreateObject("ADODB.Recordset")
Conn.Open Serv
SQL="SELECT * FROM EmailTable"
RecordView.Open SQL, Conn
Counter=0
Do While Not RecordView.EOF
Ename(Counter)=RecordView("Name")
Email(Counter)=RecordView("Email")
Counter=Counter+1
RecordView.MoveNext
Loop
output="verify=" & Ename(Counter-1)& " " & Email(Counter-1)
Response.Write output
RecordView.Close
Conn.Close
Set RecordView = Nothing
Set Conn = Nothing
%>
The button script requires no posting of variables because all the information is being pulled out of the
database. Set the URL to the one for your server in the following script:
on (release) {
loadVariablesNum
("http://your.URL.com/ASPbase/VerifyRecord.asp", 0);
}
page 121
Server-Side Flash: Scripts, Databases, and Dynamic Development
Create the two dynamic text fields and two input text fields that you need in the Text Fields layer by
following these steps:
1. Create the ID text field by using the Text tool and position it to the left of the ID button.
2. In the Text Options panel, select Dynamic Text, mark the Border/Bk check box, and
enter ID as the variable name.
3. Create the verification field with the Text tool and place it above the Verify Record
button.
4. In the Text Options panel, leave Border/Bk unchecked and enter the variable name
Verify.
5. Create two input text fields, one each for the name and e-mail data to be entered.
6. In the Text Options panel, make sure that you check the Border/Bk check box for
each field and enter the variable names Name and Email respectively.
The data entered into the two input fields is sent along with the value generated in the ID field to the
ASP page that sends the data to the appropriate field in the Microsoft Access 2000 database file on the
server. Figure 3-18 shows what the user sees after he or she enters data (with the sent to
database message disabled).
Figure 3-18: Flash can use its capability to host multiple forms and buttons with ActionScripts to effectively
organize data in a database such as that of Microsoft Access 2000.
Summary
The introductory materials in this chapter are designed primarily to show how Flash and ASP can work
together and with databases. Although this chapter just scratches the surface of what Flash 5,
ActionScript, ASP, SQL and Microsoft Access 2000 can do, we hope that you can see the potential in
the connection between Flash and server-side scripts and data sources. The most important knowledge
you should take away from this chapter is how the linkages between Flash and ASP scripts work. ASP
offers far more than we can cover in this chapter, but if you like the way ASP works, we encourage you
to look into it further. The easiest part is making the connection between Flash and ASP, especially
compared to making the connections between ASP and databases. Delving further into ASP gives you
far more tools to complete the tasks that you want to accomplish.
page 122
Server-Side Flash: Scripts, Databases, and Dynamic Development
The next chapter provides an alternative to ASP called PHP. In some respects, the two server-side
languages are the same, but they have many differences as well. If this is the first time you’ve examined
back-end computers and the use of databases over the Web, you are in a great position to compare
different approaches to server-side computing.
to access my PHP file. The addressing process is identical to HTML files, but you have to keep in mind
the file’s relative relationship to the Web server’s root directory.
If you have installed the Apache server from the CD-ROM on your PC and you are using localhost
as your Web server, put the PHP files into the htdocs directory in your Apache installation directory.
You would access PHP files saved in the htdocs directory with the following line:
http://localhostPHP/myProgram.php
But as with files saved on the JTLNet server, I recommend creating a folder within the htdocs directory
for your PHP files. Just open the htdocs directory and create a folder (a directory) for your PHP files.
For example, to address a folder named Flash5PHP with your PHP programs saved in it on your own
computer’s Apache server, you would use the following line:
http://localhostPHP/Flash5PHP/myProgram.php
PHP has three options for starting and ending tags to contain a PHP script.
Option 1:
<?php
PHP script
?>
page 123
Server-Side Flash: Scripts, Databases, and Dynamic Development
Option 2:
<?
PHP script
?>
Option 3:
<script language="php">
PHP script
</script>
For this book, we use Option 1. We like it because the beginning tag clarifies the fact that the script is
PHP without a great deal of extra effort. The other two methods work fine, and you can substitute one of
them if you prefer.
Use a text editor like Notepad (Windows) or SimpleText (Macintosh) to write your PHP scripts. To get
started, write the following script:
<?php
phpinfo();
?>
Caution If you use Notepad, make sure that Notepad doesn’t add a txt extension to
your php extension when you save your file as a text file. Place quotation
marks around the name of your file when you save it to prevent Notepad from
adding the unwanted txt extension.
Save the file as phpinfo.php in your server root directory or subdirectory. For this example, we’ve
saved our PHP file in a folder (directory) named FlashPHP in our Web server’s root directory,
www.sandlight.com. To launch the program, we would type
http://www.sandlight.com/FlashPHP/php.info.php
Substitute your domain name for www.sandlight.com and your directory name for FlashPHP. If
you’re using localhost, you would type in the following line, making the appropriate substitutions for
the subdirectory name:
http://localhost/FlashPHP/php.info.php
Figure 4-1 shows what you should see if everything is in the right place and installed correctly. If you
see the page depicted in Figure 4-1 (or one looking close to it), you have correctly accessed PHP in
your Web server.
page 124
Server-Side Flash: Scripts, Databases, and Dynamic Development
Like ActionScript, PHP expects a semi-colon at the end of most lines. But PHP is stricter about semi-
colons than ActionScript is. If you leave a semi-colon out of a certain PHP lines, the program will not
execute. This simple variable definition, for example, requires that the variable declaration itself have a
semi-colon at the end of the line:
<?php
$score = 50;
?>
The semi-colon is the instructor terminator for statements. But like ActionScript conditional statements,
PHP conditional statements never have semi-colons after a curly brace. The following example shows
where the semi-colons belong:
<?php
if ($topScore => $currentScore) {
page 125
Server-Side Flash: Scripts, Databases, and Dynamic Development
PHP is very unforgiving when it comes to semi-colons at the end of a command line, so keep an eye out
to make sure your script contains the semi-colons it needs. When you debug your script, first check to
see whether your semi-colons are where they belong.
Comments
Comments in code help developers remember what they were doing with the code when they were
developing it. PHP has several options for flagging comments, but throughout this chapter and
elsewhere in the book, we use the same convention as used in ActionScript: the double forward slash
(//). The following example shows the correct use of comments in a PHP script:
<?php
$item += $item * .07;
//The item must include a 7% sales tax.
echo $item;
?>
The comment line is another exception to the semi-colon requirement. You can write anything in a
comment line because as soon as the parser sees the two slashes, it ignores the entire line.
Escape characters
Also like ActionScript, PHP uses the backslash as an escape character so that certain characters, such
as quotation marks, may be displayed and not parsed as part of the running script. The following script,
for example, escapes the quotation marks around the nickname “Speedo.”
<?php
$move = "They called him \"Speedo,\" but his real name was Mr. Earl.";
echo $move;
?>
When the program is executed, the viewer sees the following on the screen:
They called him "Speedo," but his real name was Mr. Earl.
Initially, the only character you have to remember to escape is the double quote mark ("). But when
preparing data for a MySQL database, other characters need to be escaped, such as the single quote
mark (') and the ampersand (&). PHP can handle either character without escaping them, but the
database cannot. PHP’s addslashes() function helps take care of the problem by adding the needed
slashes automatically when the PHP script is used to add data to a MySQL database. Another function,
stripslashes(), can then be used to remove the slashes so they won’t cause a parsing problem
with PHP.
Declaring variables
Declaring a variable in PHP is not unlike doing so in ActionScript except that all variables in PHP are
preceded by a dollar sign ($) and they are case-sensitive. The following script shows the three data
types, integers, doubles (floating-point numbers), and string literals, entered into PHP variables:
<?php
$wholeThing = 6744;
$someFractions=22.95;
$stringBean= "Eat your vegetables!";
echo "<br>$wholeThing";
echo "<br>$someFractions";
page 126
Server-Side Flash: Scripts, Databases, and Dynamic Development
echo "<br>$stringBean";
?>
In PHP, however, all of these variables are different. So make sure that all the
ActionScript variables you are using in conjunction with PHP are case-
sensitive. In that way, you won’t run into a problem because you expect a
PHP variable named $Salestax to read your ActionScript variable named
SalesTax. Other than case-sensitivity, other naming conventions in
ActionScript and PHP are pretty much the same. The Hit_Score variable in
ActionScript will be equated with the $Hit_Score variable in PHP.
page 127
Server-Side Flash: Scripts, Databases, and Dynamic Development
Conditionals
The conditional statements in PHP4 are very similar, but not identical, to those in ActionScript. PHP4
supports three different statements for branching a script.
The if statement
PHP4 uses the if statement in the same way as ActionScript does. When the condition in parentheses
is met, the program executes the next line. If the condition is not met, the code in the next line is
ignored. For example, the following code triggers the echo line:
<?php
$apples=10;
$oranges=20;
if ($apples != $oranges) {
echo "I didn’t think so.";
}
?>
page 128
Server-Side Flash: Scripts, Databases, and Dynamic Development
Note in the preceding script how the logical AND (&&) operator is used in the script. Both PHP4 and
Flash 5 use logical operators in the same way.
Like the operators in PHP4 and ActionScript, very few differences exist between ActionScript and PHP
conditional statements. Conditional statements are important for server-side scripts because such
statements are the decision-makers. On dynamic sites, the data from the Flash 5 front end often has to
be analyzed in a PHP script, so noting the similarities and differences between formatting conditional
statements in ActionScript and in PHP is important.
Loops
PHP has three types of loops, and they are structured very similar to ActionScript loops.
page 129
Server-Side Flash: Scripts, Databases, and Dynamic Development
Arrays
The concept of arrays is identical in both ActionScript and PHP, and the differences are minor. Arrays
are especially important in PHP for organizing database information. PHP has a number of different
ways to create an array. First, you can just use an array name and assign literal values to each element
in the array. For example, the following is a simple array in PHP:
<?php
$item[0] = "monitor";
$item[1] = "keyboard";
$item[2] = "motherboard";
$item[3] = "mouse";
?>
Like arrays in other scripting and programming languages, the initial element is the zero (0) element, not
one (1). If you list array elements with only the brackets and no numbers, PHP will automatically assign
each element’s identifier based on the order of assignment beginning with zero (0).
You can also use the array constructor to build an array. It works very much like ActionScript’s
constructor. For example, the following is an array of flowers:
<?php
$blooms = array ("rose", "daisy", "buttercup", "zinnia", "sunflower");
?>
The first value in the array is a rose and is assigned an element identifier of 0. The others are assigned
element numbers sequentially, so sunflower would be element four (4). The following script would echo
a rose and a buttercup:
<?php
echo $blooms[0];
echo $blooms[2];
?>
A nice array feature of PHP is the ability to set the index. A special array operator, =>, sets the
sequence. For example, if you wanted your $blooms array to begin with 1 instead of 0, you could write
the following:
<?php
$blooms = array (1 => "rose", "daisy", "buttercup", "zinnia", "sun flower");
?>
With these changes, the array elements are now rose=1, daisy=2, buttercup=3, and so forth. In addition
to renumbering, you can use the => operator to create string-indexed arrays. The following code, for
example, uses abbreviations for car models to index an array of those models:
<?php
page 130
Server-Side Flash: Scripts, Databases, and Dynamic Development
$RollsRoyce = array ("SG" => "Silver Ghost", "PH" => "Phantom", "SC" => "Silver Cloud", "SS" =>
"Silver Shadow", "SSpur" => "Silver Spur");
echo $RollsRoyce[SC];
?>
In the example, the echo statement returns Silver Cloud because the string index SC has been
associated with the string literal Silver Cloud in the array. Note in the script that the index in the
echo statement was not surrounded by quotation marks ($RollsRoyce[SC] instead of
$RollsRoyce["SC"]).
Functions
Like ActionScript, PHP has both built-in functions and user functions. For example, the phpinfo()
function, used previously in this chapter, is built into PHP4. A number of other functions are built into
PHP as well, but we discuss only a small subset of these in this book as they are used with Flash 5.
(See the PHP manual at www.php.net for a full listing of functions in PHP4 along with detailed
explanations.) User functions in both ActionScript and PHP are similar in structure and application. A
user function is defined with a word using optional arguments and then a list of statements. For
example, a function to add tax and shipping to an item could be written as follows:
<?php
function taxShip ($item) {
return $item + ($item *.07) +4.95;
}
echo taxShip(19.95);
?>
The trick is, of course, to get the input from Flash 5 and use the data to do something. Eventually, you
want to be able to use PHP to take the Flash 5 data and put it into a data file. You also want to be able
to pull data out of a file and output it in a Flash 5 movie.
page 131
Server-Side Flash: Scripts, Databases, and Dynamic Development
No spaces are allowed between the variable name, the equal sign (=), and the variable’s contents. New
variables are separated by an ampersand (&) and follow the same rules as the initial variable, and no
spaces are allowed between the end of the first variable’s data and the ampersand.
Note Optionally, you can place an ampersand (&) before the initial variable name.
Some developers like to place the ampersand before the first variable so that
identifying all of the variables is easier because they all contain a leading
ampersand.
In PHP scripts, all of the variables are placed between quotation marks. The PHP echo command
sends the text block to Flash. The following script, for example, places a variable named
myHotVariable into Flash when the loadVariablesNum() action targets the PHP file.
<?php
echo "myHotVariable=This message is from a server-side script." ;
?>
This next Flash movie shows the steps involved in pulling data from a PHP script and displaying it in
Flash 5. The movie contains the following layers:
Text Field
Button
Background
Save the movie as LoadPHP1.fla.
Color palette
All color palettes are from a set of color combinations that complement one another and help improve
the general appearance of the movie. You add each color by first using the values (hexadecimal) for
each color in the Mixer panel and then selecting Add Swatch from the pop-up menu in the Mixer panel’s
upper-right corner. Table 4-2 shows the color palette for LoadPHP1.fla.
Table 4-2: Color Palette for LoadPHP1.fla
Color R Value G Value B Value
A EE 19 00
B 00 17 D7
C 8A B0 D7
D EE F3 E6
E 00 00 00
Background layer
The background layer is made up of a red (Color A) rectangle on top of the movie’s background color
(Color D). Select Modify, Movie and choose Color D from the movie’s color palette. Then use the Align
panel to center the rectangle to the stage’s center. Lock the layer when you are finished. Figure 4-2
shows how the background looks on the stage.
page 132
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 4-2: The stage area contains a single text field and a button for the ActionScript.
Button layer
The button holds the ActionScript that loads the variables from PHP. This next set of steps shows how
to set it up:
1.Use the Oval tool to draw a circle and use Color B for the fill and Color C for the
stroke. Using the Text tool, type PHP on top of the button.
page 133
Server-Side Flash: Scripts, Databases, and Dynamic Development
2.Select the circle and text and press the F8 key to open the Symbol Properties dialog
box. Select Button for the Behavior, and in the Name window, type phpbutton.
Click OK to create a button symbol.
3.Select the button instance and click the Action panel icon (arrow) on the launcher bar
to open the Objects Action panel. Enter the following script, substituting the URL
with the one you use as your root directory and subdirectory in your root directory:
4. on (release) {
5. loadVariablesNum ("http://www.sandlight.com/
6. PHP/data.php", 0);
}
7.When you enter the ActionScript in Normal mode, place the parameter values as
shown in Figure 4-3. Use the default Level value of 0, and type in the URL in the
URL window. You do not want to send any variable to PHP so leave the Variables
pop-up menu in the default state of Don’t send.
Figure 4-3: In the Normal mode, the parameter values are placed at the bottom of the
ActionScript editor.
page 134
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 4-4: The text field associated with the variable name displays the contents from the server-side
script.
page 135
Server-Side Flash: Scripts, Databases, and Dynamic Development
Color palette
Use the color palette in Table 4-3 for the movie. Use Color B for the background color.
Table 4-3: Color Palette for LoadPHP2.fla
Input layer
In this movie, both an input and output layer are required. Figure 4-5 shows an overview of the movie
with the text field used for input at the top of the stage.
Figure 4-5: Two text fields provide an entry portal to PHP (input) and a return data window from PHP
(output); a button contains the ActionScript necessary to launch the process.
This next set of steps covers the process for creating the Input text field:
1.Use the Rectangle tool to draw a background for the text field. Use Color A as the fill
color and Color D as the stroke color.
page 136
Server-Side Flash: Scripts, Databases, and Dynamic Development
2.Select the Text tool and draw a rectangular text field over the background rectangle
as shown in Figure 4-5. Open the Text Options panel and select Input Text from
the top pop-up menu.
3.In the Variable box on the Text Options panel, type input for the variable name to be
associated with the text field.
Output layer
The Output text field goes directly below the Input text field, as shown in Figure 4-5. Follow the steps for
the Input layer except select Dynamic Text from the pop-up menu in the Text Options panel and type
output for the variable name to associate with the text field.
Button layer
The button holds the ActionScript that loads the variables from PHP. This next set of steps shows how
to set it up:
1.Use the Oval tool to draw a circle, using Color D for the fill and Color C for the stroke.
2.Select the circle and press the F8 key to open the Symbol Properties dialog box.
Select Button for the Behavior, and in the Name box, type postbutton. Click OK to
create a button symbol.
3.Select the button instance and click the Action panel icon (arrow) on the launcher bar
to open the Objects Action panel. Enter the following script, substituting your own
path:
4. on (release) {
5. loadVariablesNum ("http://www.sandlight.com/PHP/data2.php", 0, "GET");
}
While entering the ActionScript in the Normal mode, place the parameter values as shown in Figure 4-6.
Use the default Level value of 0, and type in the URL in the URL box. In the Variables pop-up window,
select Send using GET. That completes the Flash side of the equation.
Figure 4-6: All variables in the Flash movie are sent using Send using GET.
page 137
Server-Side Flash: Scripts, Databases, and Dynamic Development
sends the variable $output back to Flash. Save the following script under the name data2.php in
your root directory or the subdirectory in the root directory:
<?php
$input .= " from php";
$output= "output=$input";
echo $output ;
?>
Run your SWF file and enter some text in the input text field. As shown in Figure 4-7, whatever you
enter in Flash bounces back from PHP with the concatenated message.
Figure 4-7: The input from Flash is modified in PHP and returned as output in Flash.
The next step is to see how data gathered in a Flash front end can be used in calculations generated by
PHP. Even though most calculations could be accomplished by client-side scripts in ActionScript,
seeing how to pass calculated data from a PHP script with data originating in Flash is the first step in
using wholly PHP-generated data for output in Flash.
This next Flash movie is similar to the previous one, but it takes the data sent from Flash, performs a
calculation, and then returns the calculated results back to Flash. In this movie, you can begin to see
the benefits of PHP. Several different Flash movies could use the same PHP script, and if values need
to be changed (tax rates or shipping costs, for example), a single change in the PHP script would suffice
to change the output in all the Flash movies that need the same data calculated. This movie has the
same three layers as the previous movie:
Button
Input
Output
Save the movie as LoadPHP3.fla.
page 138
Server-Side Flash: Scripts, Databases, and Dynamic Development
Color palette
Use the color palette in Table 4-4 for the movie. Use Color B (deep red/brown) for the background color.
Table 4-4: Color Palette for LoadPHP3.fla
Input layer
Like the last movie, the input field is used to provide data associated with a variable that is sent to the
PHP script on the server. This next set of steps covers the process for creating the input text field:
1.Select the Text tool and draw a rectangular text field near the top of the stage, as
shown in Figure 4-8. Open the Text Options panel and select Input Text from the
top pop-up menu. In the Variable box on the Text Options panel, type input for the
variable name to be associated with the text field.
Figure 4-8: The first text field is used to input data that is sent to the PHP script, calculated,
and then returned to Flash in the output window.
2.In the Character panel, select Verdana as the type and black for the text color.
3.Using Color C and a bold Verdana 12-point font, type in Enter item price: as shown
in Figure 4-8.
page 139
Server-Side Flash: Scripts, Databases, and Dynamic Development
Button layer
The ActionScript in the button sends data to the PHP script, but it does no calculation itself. The script is
almost identical to the script in the previous Flash movie, but the button is a little different:
1.Use the Oval tool to draw an oval, using Color A for the fill and white for the stroke.
Type Total on top of the oval.
2.Select the oval and text on the oval and press the F8 key to open the Symbol
Properties dialog box. Select Button for the Behavior, and in the Name box, type
calcToPHP. Click OK to create a button symbol.
3.Select the button instance and click the Action panel icon (arrow) on the launcher bar
to open the Objects Action panel. Enter the following script, substituting your own
path:
4. on (release) {
5. loadVariablesNum ("http://www.sandlight.com/PHP/data3.php", 0, "GET");
}
6.Use the default Level value of 0, and type in the URL in the URL window. In the
Variables pop-up window, select Send using GET.
Output layer
The output text field goes below the button as shown in Figure 4-8. Follow the steps for the Input layer
except select Dynamic Text from the pop-up menu in the Text Options panel and type output for the
variable name to associate with the field. Also, enter Total cost as the label for the field.
PHP calculations
This next PHP script does the relatively mundane chore of adding tax and shipping costs to a value.
Like the script in the previous movie, this script wraps the result into a variable and sends it back to
Flash with the echo command:
<?php
$input += $input * .07;
$input = $input +5.99;
$output= "output=$input";
echo $output ;
?>
Save the PHP file as data3.php and place it in your root directory or the subdirectory in the root
directory. When you launch your Flash SWF file, the value you enter into the input text field is put into
the calculations of the PHP script. Because the text field is associated with the input variable in Flash
ActionScript, the data is passed to the $input variable in PHP. The calculations are carried out and the
results are returned to the output variable in Flash. Because the second text field is associated with
the output variable, the results appear in the text field window.
page 140
Server-Side Flash: Scripts, Databases, and Dynamic Development
The function name and arguments are standard, as are the calculations and formatting statements. But
once all of the formatting is completed and stored in PHP variables, the Flash variables have to be
formatted to read the PHP variables while they are within the function’s curly braces. The echo
command replaces the return statement in the function, but the format is almost identical to the
previous functions section. The following function, for example, is another tax and shipping one; but the
Flash formatting has been added to this function. When the function is called from Flash, it returns the
input value from Flash with the tax and shipping added.
<?php
function taxShip ($item) {
$total=$item + ($item *.06) +4.95;
$output="output=$total";
echo $output;
}
taxShip($input);
?>
Save this the PHP file as taxShipFunction.php in your root directory on the server. Then, using the
movie from the previous example (LoadPHP3.fla), change the button script to read as follows:
on (release) {
loadVariablesNum
("http://www.sandlight.com/PHP/taxShipFunction.php", 0,
"GET");
}
Try out the movie by pressing Ctrl+Enter (Windows) or Cmd+Return (Macintosh). When the SWF file
appears, type in a value and click the button. You should see the value you entered returned with tax
and shipping costs added, as shown in Figure 4-9.
Figure 4-9: The data in the Total cost field was generated through calculations in a PHP script and returned
to Flash for output.
page 141
Server-Side Flash: Scripts, Databases, and Dynamic Development
The process of passing array elements between Flash 5 and PHP is important to understand because
you can place data from a database into an array for transfer to and from Flash and PHP. Arrays are
treated no differently from variables. The great advantage of an array, though, is that you can use a
series of numbers to access the array. By understanding how to use array elements and associated
values, you can establish a better way to organize and pass data between Flash and PHP.
On the Flash side, you can associate the arrays with text fields to display any or all elements of the
array. On the PHP side, you can coordinate the array elements to the text fields. In this way, whatever
value is passed from Flash to PHP can be used to coordinate PHP data and Flash output. This next
movie contains five text fields and five buttons associated with the text fields. Each of the text fields is
an element in an array, and each button contains a script that sends information to a PHP script that
uses its own array to verify that a button has been clicked. This movie uses the following three layers:
Background
Buttons
Text Fields
Figure 4-10 provides an overview of the movie and its major components. Save the movie as
ArrayData2.fla.
Figure 4-10: Each of the text fields is associated with an array element.
page 142
Server-Side Flash: Scripts, Databases, and Dynamic Development
Color palette
The movie uses a simple gray, purple, black, and white color scheme whose values are shown in Table
4-5.
Table 4-5: Color Palette for ArrayData2.fla
Background layer
Begin by using the purple (Color A) to color the background; choose Modify → Movie and then select
the palette’s purple color. In the Background layer, draw gray rectangles with black strokes to serve as
backdrops to the text fields as shown in Figure 4-10. Use the Info panel to set the rectangle dimensions
to W=259 and H=28. After you complete the first rectangle, select it and then choose Modify → Group
so that the stroke and fill are grouped. Then make four identical copies of the rectangle and line them up
vertically using the Align panel to space and align them.
Buttons layer
Create five buttons and label them from 1 to 5 as shown in Figure 4-10. Then create a sixth button and
label it Reset.
Array buttons
The buttons adjacent to the text fields contain scripts that send (POST) data to the PHP script and fire
the PHP script. The value of the myData variable is the array element value of the text field adjacent to
the button. The PHP script shows how that value is used to return the correct message when the button
is clicked. Substitute your URL for the one provided.
on (release) {
myData = 1;
loadVariablesNum ("http://www.sandlight.com/PHP/arrayData2.php", 0, "POST");
}
Reset button
The Reset button launches a PHP script that places a space in each of the five text fields, effectively
resetting them all.
on (release) {
loadVariablesNum ("http://www.sandlight.com/PHP/arrayClear.php", 0);
}
page 143
Server-Side Flash: Scripts, Databases, and Dynamic Development
Tip You can save some time by selecting the first text field and then using Alt+drag
(Windows) or Option+drag (Macintosh) to make copies of the text field. Then all
you need to do is to align the new fields and rename the elements in the Text
Options panel.
PHP scripts
Two PHP scripts are required for the movie. The first script generates an array and then, depending on
the button clicked in the Flash movie, sends an array element back to Flash in a text field associated
with the output array (out[n]). The important part of the script is where the $output variable uses the
value of $myData, which was sent as myData from Flash. Each numbered button’s script sends a
value in myData consistent with the text field’s element number next to the button. The value is also
linked to a value in the array in the PHP script. Thus, the button numbered 3 sends a value of 3 in the
myData variable. In the PHP script, $item[3] states "You clicked the third button" and
appears in the text field associated with out[3] in the Flash movie. All of these elements are placed in
the $output variable by concatenating the array element out[$myData] with the equal sign (=) and
with the PHP array element $item[$myData]. Then the whole thing is echoed back to Flash. Save the
script in the server’s root directory or in a subdirectory in the root directory under the name
arrayData2.php.
<?php
//Create a simple array.
$item[1] = "You clicked the first button.";
$item[2] = "You clicked the second button.";
$item[3] = "You clicked the third button.";
$item[4] = "You clicked the fourth button.";
$item[5] = "You clicked the fifth button.";
page 144
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 4-11: Arrays written in PHP can connect with an array in ActionScript.
As a front end, Flash 5 serves to provide a portal to data access and storage. Using ActionScript, Flash
5 sends data to PHP, which in turn retrieves or stores the data in the database by translating the
request into a language the RDBMS can understand. If a request for data is made, PHP sends the
query on to the RDBMS, which sends the information back to PHP, which translates it for Flash 5. Like
PHP and ActionScript, RDBMS have their own languages, so all of the languages have to be
coordinated. Think of PHP as a translator who speaks both ActionScript and RDBMS.
One of the most popular RDBMS used on the Web is MySQL. MySQL can be downloaded and used for
professional database development. Although you can use it without charge for learning and most
personal uses, a small fee is required for commercial uses. Like PHP, MySQL is Open Source
Software, so can you modify it to best suit your needs. Versions of MySQL are available for Windows,
MacOS X Server (PowerPC), Unix, and Linux. At this writing, the latest version is 3.23.29a-gamma; by
the time you read this book, a later version will no doubt be available. Check out www.mysql.com for
the newest version and full support of this language.
The focal point of this section involves a three-language link. MySQL has its own database language
(SQL is an acronym for Structured Query Language), including a whole set of commands for creating
databases and tables and entering and retrieving data. PHP has a special subset of functions dedicated
to MySQL, and all of this data has to be handed off to ActionScript. The major work is getting a good
clear communication link between PHP and MySQL, and PHP provides several MySQL functions to
make that job relatively easy. Figure 4-12 shows the relationship between Flash, PHP, and MySQL.
page 145
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 4-12: PHP is the translator between Flash 5’s ActionScript and MySQL.
mysql>
15. Exit the MySQL monitor by typing exit. You should see the C:\mysql\bin> cursor.
16. Type mysqladmin flush-privileges and press Enter. That command allows the user,
willie, to access the databases with the password yourOwnPW.
17. To establish the current user, re-enter the MySQL monitor using the following
command sequence (shown with MySQL responses):
18. C:\mysql\bin>mysql -h localhost -u willie -p
19. Enter password: *******
20. Welcome to the MySQL monitor. Commands end with ; or \g.
21. Your MySQL connection id is 15 to server version: 3.23.29a-gamma-debug
22. Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer
23.
24. mysql>
page 146
Server-Side Flash: Scripts, Databases, and Dynamic Development
Setting up MySQL usually isn’t so onerous after you have established a user host and password.
Usually, you start the MySQL monitor by using steps 1 through 3 and 8 only.
MySQL responds to this command with something similar to the following display:
+-----------+
| Database |
+-----------+
| flashbase |
| flashtab |
| mysql |
| test |
+-----------+
4 rows in set (0.00 sec)
The command displays all the established databases. The databases named mysql and test are
established by default. The flashbase database is the one just created, and flashtab is an
additional user-defined database. As you can see, creating a new database is straightforward and
simple.
To add a table to the database, first issue a USE flashbase; command to select the desired
database. The next step is to create a table to show the e-mail addresses of a list of people stored in a
database. Each field in the table must include a name, a data type, and the length of the field. Table 4-6
lists a sample of the main data types.
Table 4-6: MySQL Data Types
page 147
Server-Side Flash: Scripts, Databases, and Dynamic Development
For the example in this chapter, the table has only two columns (fields). One holds an individual’s name
and the other holds an e-mail address. The name field (ename) uses a fixed-length string of 30
characters, and the e-mail field (email) uses a fixed-length string of 40 characters.
Note Whenever you press the Enter key without a semi-colon when in the MySQL
monitor, the next line is indicated by a -> symbol where you can add more code to
the command line or statement. As soon as the semi-colon is in place, the
command line is terminated, and the command is issued.
To create a table in the flashbase database, make sure that the database is still selected and then
enter the following code:
mysql> CREATE TABLE emailflash (
-> ename CHAR(30),
-> email CHAR(40)
-> );
page 148
Server-Side Flash: Scripts, Databases, and Dynamic Development
mysql>
Practice with the basic MySQL commands. Enter records into a table and select records from a table to
get the feel of the commands. In the next section, you will see how to link PHP with MySQL and get
information from a MySQL database using PHP. Once the data has been passed to PHP, getting it into
Flash is relatively easy. Likewise, sending data from Flash to MySQL involves simply taking data from
Flash, sending it to PHP, and then sending it on to MySQL.
Working with MySQL or PHP separately is fairly simple. But when you use your own computer for a
server and client with both, you may find that you spend more time dealing with errors resulting from
access privileges in MySQL than learning how to make the three-way connection between Flash, PHP,
and MySQL. To simplify matters and provide experience working in a real-world developing
environment, the examples and explanations in this section use JTLNet’s MySQL.
page 149
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 4-13: The username and password help establish the security parameters for
MySQL.
3.In the Db: text box, type the name for a database. Figure 4-14 shows a database to
be added named flashook. Click the Add Db button to insert the database into your
MySQL account.
4.In the UserName text box, type a username you want. In the Password text box, type
a password. Figure 4-14 shows joe for the username and coolbeans for the
password. Click the Add User button.
Figure 4-14: You must add at least one database and user to MySQL on the hosting
service.
After you have added the database and user, you will find that their names have been
altered. Both the database and the username will have your account username attached to
the beginning of the names you entered. Your database will now be
accountName_username. In the example, the sample account is called sandligh, and so
now the database’s name is sandligh_flashook. (The appended account name is the
hosting service’s convention and not a MySQL requirement. Different hosting services may
page 150
Server-Side Flash: Scripts, Databases, and Dynamic Development
Once you have established a database and an associated user, you are all set to start writing PHP
scripts that access the database in your JTLNet site. (If you have a different hosting service that
provides MySQL, check with it to see about setting up your databases.)
Most hosting services do not allow direct access to your MySQL through Telnet but do provide
alternatives for examining your MySQL databases. JTLNet provides an online program called
phpMyAdmin for administering MySQL databases. If you add your own tables and records from the
PHP scripts provided in this book, you do not need to use phpMyAdmin, but you will find it handy for
inspecting your MySQL database. You can use the same commands as you do with the MySQL
monitor. Figure 4-15 shows one of the screens from phpMyAdmin where a MySQL command is issued.
Clicking the Go button issues the command.
This next section introduces several PHP functions specifically for MySQL. Table 4-7 provides an
overview and summary of the functions that are used. (For a full list of PHP MySQL functions, see
www.php.net/manual/ref.mysql.php.)
Figure 4-15: From the phpMyAdmin utility, you can write SQL queries similar to those issued in the MySQL
monitor.
page 151
Server-Side Flash: Scripts, Databases, and Dynamic Development
Function Result
mysql_connect Establishes a connection to a MySQL Server
mysql_num_rows Returns the number of rows in result
mysql_query Sends a MySQL query
mysql_result Gets result data
mysql_select_db Chooses a MySQL database
if ($hookup) {
$feedback="You’re hooked up Ace.";
}
echo "$feedback";
?>
Save the script in the root directory of your server or a directory within the root directory as
first_connect.php. In JTLNet, the root directory would be the public_html directory. We added the
scripts subdirectory to store the PHP scripts for MySQL, so for us the URL to launch the script would
be
http://www.sandlight.com/scripts/first_connect.php
The server is named localhost in the JTLNet setup so that the name is used in the connection. One
of the users was defined as sandligh_willie with the password yourOwnPW. So if all goes as
planned, you will see the good news, "You’re hooked up Ace." If you fail to make the connection,
you will see a message like the following in your browser:
Warning: MySQL Connection Failed: Access denied for user:
‘sandligh_willie@localhost’ (Using password: YES) in
/home/sandligh/public_html/scripts/first_connect.php on line 8
No joy Ace.
page 152
Server-Side Flash: Scripts, Databases, and Dynamic Development
If your connection fails, check your script to make sure the server name, username, and password are
correct. If they are correct, then you need to make sure that on your hosting service you have
established the correct user and databases and have connected the user and database. The greatest
number of problems you will encounter are going to be with the security setup of MySQL, but once you
have a good connection, the rest is relatively easy.
Selecting a database
The next step is to select the database you plan to use with the PHP function
mysql_select_db(databaseName, connection). The database name is the name you have
given the database on the host. The connection name is the variable where the mysql_connect()
data are stored. In this example, an at sign (@) is placed in front of the mysql_select_db function to
suppress the automatic feedback to the Web page. This sign ensures that only the die() function
message will be displayed.
<?php
if ($debase) {
$feedback="Database is selected and ready to go.";
}
echo "$feedback";
?>
Once you are able to connect to MySQL and the desired database, the rest is pretty smooth sailing.
Note We found that far fewer problems occurred when using the hosting service than
when attempting to run both the Apache server and MySQL monitor on our own
computers. Several security problems kept cropping up with MySQL, and
although everything worked great when no security conflicts were detected, the
security conflicts kept reoccurring at different times for no apparent reasons.
page 153
Server-Side Flash: Scripts, Databases, and Dynamic Development
using JTLNet, use the server name in the listing, but otherwise change it to the name that is appropriate
to your hosting service.
<?php
if ($result) {
echo "Table has been created.";
}
?>
Save the script as add_table.php and launch it from your browser. If you get any result other than
"Table has been created," check your script and the names of the different connections.
page 154
Server-Side Flash: Scripts, Databases, and Dynamic Development
?>
Save the PHP file as flash_in_new_records.php and put it in your root directory or in a folder in
the root directory. Flash accesses this file, and the GET method sends variables from Flash to PHP.
Figure 4-16: An input movie sends information for two fields to the MySQL database.
page 155
Server-Side Flash: Scripts, Databases, and Dynamic Development
Button layer
The button’s sole purpose is to contain a single script to fire the PHP script:
1. Use the Oval tool to draw a circle.
2. Select the circle and press the F8 key to open the Symbol Properties dialog box.
Select Button for Behavior and enter FireInput as the name. Click OK.
3. Select the button and open the ActionScript editor. Then enter the following
script substituting your own domain name or IP address:
on (release) {
loadVariablesNum ("http://www.sandlight.com/scripts/flash_in_new_records.php",
0, "GET");
}
Although creating the Flash movie is quite easy, the movie provides a great deal of help in managing
the database. Instead of having to use the MySQL commands either in the MySQL monitor or through
phpMyAdmin in the hosting service, you can just type a name and e-mail address in Flash and click the
button.
You can change the row value (1) to anything you want as long as your number is from 0 to the number
of rows in your table minus 1. (If you have 6 rows, the top row would be 5 because the first row is 0.)
Because the ename field contains a name of someone, the $name variable now should contain the
name of whomever you put into the second row (row 1) of the table. To pass that name to Flash, you
need to translate it into a format that Flash understands. The following line does that:
$name ="name=$name";
You should have a text field with the name variable in your Flash 5 movie so that when the echo
"$name"; statement executes, you can see it on the screen.
A similar translation for the second field, email, has to have an ampersand in front of it because it is a
new variable for Flash. In the second translation line, you see an ampersand (&) attached to the
beginning of the first email in quotation marks.
$email ="&email=$email";
page 156
Server-Side Flash: Scripts, Databases, and Dynamic Development
Without the ampersand, Flash would treat the data from $email as part of the $name variable and
send the output to the variable titled name.
Save the script in Listing 4-1 as select_fields_flash.php and put it into your root directory or a
subdirectory in the root directory. After you have successfully run the program with Flash, change the
record to something other than 1 in the following lines:
$name=(mysql_result($result,1,"ename"));
and
$email =(mysql_result($result,1 ,"email"));
Make sure that the numbers you change are the same for both lines. Otherwise, the name and e-mail
won’t match one another.
Listing 4-1: The select_fields_flash.php File
<?php
$user="sandligh_willie"; //Username
$pass="yourOwnPW"; //Password
//Select database
mysql_select_db($flashbase,$hookup);
$name=(mysql_result($result,1,"ename"));
$name ="name=$name";
echo "$name";
page 157
Server-Side Flash: Scripts, Databases, and Dynamic Development
$email ="&email=$email";
echo "$email";
?>
Button layer
The ActionScript code for the button only receives data from the PHP script, so no GET method is
required. After creating a button, select it, open the Object Actions panel, and enter the following code in
the ActionScript editor substituting your own domain name or IP address:
on (release) {
loadVariablesNum ("http://www.sandlight.com/scripts/select_fields_flash.php",
0);
}
Test the movie by choosing Control → Test Movie from the menu bar. When you click the button, you
should see the name and e-mail address for the person you had entered into the MySQL database in
the second row (row 1). Change the row number in the PHP script, resave the file, and click the button
in Flash again. You should get a different record.
<?php
page 158
Server-Side Flash: Scripts, Databases, and Dynamic Development
$user="sandligh_willie"; //Username
$pass="yourOwnPW"; //Password
//Select database
mysql_select_db($flashbase,$hookup);
$name=(mysql_result($result,$rn,"ename"));
$name ="name=$name";
echo "$name";
$email ="&email=$email";
echo "$email";
?>
The Flash front end for the PHP script requires both input and output fields. The input sent to the PHP
script selects the record number for the two fields. (References to record numbers are the same as
references to row numbers in the MySQL table.) Then the PHP script queries the MySQL database and
returns the selected records to PHP and then on to output in two Flash windows: one for the name and
the other for the e-mail address. The difference is that the user controls which record number is
page 159
Server-Side Flash: Scripts, Databases, and Dynamic Development
selected. Figure 4-17 shows the SWF file along with the buttons and text fields. The button on the left is
green and increments the record number, and the red button on the right decrements the record
number, enabling the user to scroll through the records. The movie, called click_record.fla, uses
the following three layers:
Output from MySQL
Selected Record
Buttons
Figure 4-17: Two buttons in Flash control the record to be retrieved from the MySQL database.
Button layer
The Button layer has two buttons on either side of the text field that displays the record number. One
button increments the record number, and the second one decrements it. The following steps show how
to set up these buttons:
page 160
Server-Side Flash: Scripts, Databases, and Dynamic Development
1. Choose Window → Common Libraries → Buttons from the menu bar. When the
Library-Buttons.fla window appears, select the folder titled (circle) LED Button
Set. Drag one each of a red button and a green button from the folder and place
them on either side of the record display text field.
2. Double-click the green button to enter the Symbol Editing mode. Select the
button in the Up frame and change its size to W=35, H=35 using the Info panel.
Repeat the process in the Over frame. In the Down frame, change the
dimensions to W=25, H=25. Exit the Symbol Editing mode, and then re-enter the
mode by double-clicking the red button. Repeat the same process for the red
button. Exit the Symbol Editing mode.
3. Select the green button and open the Object Actions panel and ActionScript
editor by clicking the Show Actions icon on the launcher bar. Enter the following
ActionScript, substituting your own domain name or IP address for the domain
shown:
4. on (release) {
5. rn +=1;
6. loadVariablesNum ("http://www.sandlight.com/scripts/record_browse.php", 0,
7. "GET");
}
8. Select the red button and open the Object Actions panel and ActionScript editor
by clicking the Show Actions icon on the launcher bar. Enter the following
ActionScript substituting your own domain name or IP address for the domain
shown:
9. on (release) {
10. rn -=1;
11. loadVariablesNum
("http://www.sandlight.com/scripts/record_browse.php", 0,
12. "GET");
13. }
<?php
page 161
Server-Side Flash: Scripts, Databases, and Dynamic Development
$user="sandligh_willie"; //Username
$pass="yourOwnPW"; //Password
//Select database
mysql_select_db($flashbase,$hookup);
//Query specific table in database and find the number of rows in the table
$numrows=mysql_num_rows($result);
$numrows = $numrows-1;
$counter=0;
do {
$name=(mysql_result($result,$counter,"ename"));
++$counter;
$match=$counter-1;
$email = (mysql_result($result,$match,"email"));
if($search != $name) {
page 162
Server-Side Flash: Scripts, Databases, and Dynamic Development
$email ="email=$email";
echo "$email";
?>
The Flash side of the equation requires three elements: an input field, an output field, and a button to
launch the ActionScript program that fires the PHP script. To get started, create the following four layers
and save the FLA file as search_record.fla:
Background
Search Field
From Database
Button
Figure 4-18 shows the initial setup of the movie with all of its layers and components, and Table 4-8
provides the values for the color palette.
Figure 4-18: The top text field contains a search word sent to the PHP script to locate an e-mail address in
the MySQL database.
Table 4-8: Color Palette for search_record.fla
page 163
Server-Side Flash: Scripts, Databases, and Dynamic Development
Background layer
All of the labels and backdrops for the text fields are placed in this layer. The following steps explain
how to set up the layer:
1. Use Color A from the palette for the labels Search Database, Enter Name, and
Email Address.
2. With the Rectangle tool, draw the rectangle backdrops for the text fields using
Color A for the fill and Color C for the stroke. Set the stroke to 3 in the Stroke
panel. Each backdrop should have dimensions of W=220, H=28. Use Color B for
the background color.
3. Lock the layer when you are finished.
Button layer
Like the other buttons used in this chapter, this one’s primary purpose is to launch the PHP script and
send a variable originating in Flash to the PHP script:
1. Using Color A as the stroke and Color C as the fill, work with the Oval tool to
draw a circle.
2. Select the circle and Press F8 to open the Symbol Properties dialog box. Select
Button for the Behavior, name the button NowSearch, and click OK.
3. Select the button and click the Show Actions icon on the launcher bar to open
the Actions Panel and ActionScript Editor. In the ActionScript editor, type the
following script, substituting your own domain name or IP address:
4. on (release) {
5. loadVariablesNum ("http://www.sandlight.com/scripts/search_record.php", 0,
6. "GET");
7. }
Figure 4-19 shows the Flash movie in action.
page 164
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 4-19: The e-mail address in the same record as the search name is returned to an output field.
Summary
As a server-side language, PHP is very easy to use and format for use with Flash. Variables can be
passed back and forth between PHP and Flash easily using data from forms in Flash or from calculated
data stored in variables to a PHP script. In conjunction with MySQL, PHP can store data from a Flash
form in a database. Likewise, Flash can go through a PHP script to access data in a MySQL database
and show it on the screen. Also, because Flash is fully cross-browser compatible, you don’t have to
worry about creating different scripts for the different browsers when it comes to accessing data in
forms.
In Chapters 10 and 11, PHP is employed with Flash to create an eBusiness site for potential customers
and a Flash administrative tool to process orders online customers make. You will see further uses of
PHP with Flash, including a module that automatically sends an email from PHP. Because this book
only scratches the surface of what PHP can do, take a look at the many excellent PHP books that are
available.
page 165
Server-Side Flash: Scripts, Databases, and Dynamic Development
requires more than intuitively hooking up the ActionScript XML objects to a file written in XML. You can
wrestle a good deal with ActionScript only to find that the XML document is not well-formed and all the
ActionScript in the world can’t help you out. So, although this introduction to XML is hardly more than a
brief encounter, it is an important step to take before leaping into a Flash 5 example without a clue of
what XML is all about. Far from warning you off using XML with Flash 5, this chapter shows you why
you should learn everything you can about XML.
XML is for structuring data, and you need something to show that data in a useful way. Most developers
use Cascading Style Sheets (CSS). For example, the following CSS script provides formatting in the
form of a 14-point bold green font for the data in the XML file:
name {display:block; font-size: 14pt; color: #009900;font-weight: bold}
By saving the file as an external style sheet named contact.css, you can use it to format the
elements with the tag label name. Now the XML document looks like the following example:
<?xml version="1.0" ?>
<?xml-stylesheet type="text/css" href="contact.css" ?>
<eFolks>
<contact>
<name>Bill Sanders</name>
</contact>
<contact>
<name>Mark Winstanley</name>
</contact>
</eFolks>
The output is now formatted, as shown in Figure 5-1.
page 166
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-1: XML requires formatting from another source because XML does not have its own formatting
tags.
Because XML has no formatting capabilities, Flash 5 can come to the rescue and take care of the data
formatting. In previous chapters in this book, you see again and again that Flash 5 can take data out of
any database and display it in any way the developer wants. Designers have far more freedom and
options using Flash 5 to display data in text fields than they do when using HTML. And now that
ActionScript includes XML objects in its source code, using Flash 5 as a front end for XML databases is
a far better option than using limited HTML pages.
Although XML is a close cousin of HTML because both share a common ancestry in Standard
Generalized Markup Language (SGML), the two languages are very different when it comes to the rules
for writing. The following list summarizes the differences:
XML is case-sensitive, and HTML is not. So if you have a <Name> tag, do not try to use
<name> in XML.
XML has no formatting tags of its own.
The user defines the element names. (An opening and a closing tag constitute an
element: <name> </name>.)
XML requires newer browsers than HTML does. Internet Explorer 5 and Netscape
Communicator 6 are the earliest browsers that can reliably read XML.
XML is unforgiving for little mistakes, but HTML is very loose and forgiving.
All XML elements must have a closing tag (for example, <customer> and </customer>);
HTML lets you get away with a single opening tag (such as <br>).
Well-formed XML requires a Document Type Definition (DTD) or schema for each
element.
All elements are self-contained mini-XML documents.
You can add more information, such as whether the XML document depends on another XML
document or is a standalone. It defaults to standalone. You may also select from a number of encoding
values. Here is a partial list:
UTF-8: Compressed Unicode, to which XML defaults
UTD-16: Compressed Universal Character System
ISO-8859-1: Western European Languages
ISO-2022-JP: Japanese
If you want to include encoding values, you would enter the following:
<?xml version="1.0" encoding="iso-8859-1" ?>
page 167
Server-Side Flash: Scripts, Databases, and Dynamic Development
But for most applications that are not linked to another XML file, all you need is the version number in
your declaration.
</eFolks>
The name eFolks can be in all uppercase, all lowercase, or a combination as used in the example.
Remember, though, that whatever combination of cases you use, you will be using that same
combination throughout the document. Unlike HTML, which is not case-sensitive, XML very much is.
Methods Properties
appendChild firstChild
hasChildNodes lastChild
nextSibling
parentNode
previousSibling
After you declare your document and root elements, you can declare all the other elements in your XML
document:
<?xml version="1.0" ?>
<eFolks>
<contact>
<name>Bill Sanders</name>
<email>[email protected]</email>
</contact>
<contact>
page 168
Server-Side Flash: Scripts, Databases, and Dynamic Development
<name>Mark Winstanley</name>
<email>[email protected]</email>
</contact>
</eFolks>
In the preceding example, the XML document now has the following four elements:
eFolks
contact
name
email
The example uses repeated elements. The root element appears only once, but all other elements can
repeat as often as needed. For example, the contact, name, and email elements are all employed
twice.
Understanding and correctly using document type definitions (DTD) with XML pages can be a bit tricky,
and unless you are careful, you can create a poorly formed XML file that doesn’t work correctly when
you attempt to load data from the file into Flash. Basically, DTD tells the parser what type of data can be
expected in the different elements that make up your page. If you do not provide the right information,
problems occur. In the simple pages demonstrated so far, we have not bothered to include a DTD, but
not doing so severely restricts what can be done with the data. DTD is the connection between the XML
processor and the application receiving the data.
The format for an internal DTD begins with the following lines:
<!DOCTYPE rootElement [
<!ELEMENT rootElement (element[s] or dataType) >
]>
Because the oneTrick.xml file has only a single element, the root element is described as a data
type, #PCDATA (character data), instead of in terms of the elements that it embodies. Usually, the root
element consists of one or more other elements, but this simple example shows a minimalist and
(almost) bulletproof instance of how to work with DTD.
Note A developing alternative to DTD is schema. Like DTD, schema is a set of
validation rules for XML documents, but it is written in XML style and enables you
to validate data types such as integer, time, and date. World Wide Web
Consortium (W3C) is working on a schema recommendation, and Microsoft
Corporation has developed its own schema vocabulary that can be learned and
used. To see W3C’s progress on its schema draft and Microsoft’s schema, visit
www.w3.org/TR/xmlschema-1/ and
http://msdn.microsoft.com/xml/reference/schema/start.asp.
page 169
Server-Side Flash: Scripts, Databases, and Dynamic Development
XML validation
Because both Internet Explorer 5 and Netscape Communicator 6 can parse XML, you would think they
could validate the code as well. They cannot. But if you attempt to bring invalid XML into Flash 5, you
can run into problems. Before you start thinking about the ActionScript, you need to work with XML and
to validate your XML with a validation application. If you make a mistake in your DTD, a validation
program makes that fact abundantly clear.
Several applications are available for XML validation, but my favorite is at Brown University. The URL
for the Scholarly Technology Group’s validation page at Brown is
www.stg.brown.edu/service/xmlvalid/. The initial page provides a window where you can
browse your hard drive for your XML files, as shown in Figure 5-2.
Figure 5-2: An online validation form enables you to check the validity of your XML and DTD.
After you select the file that you want to validate, click the Validate button (refer to Figure 5-2). If your
XML file is well-formed, you see a validation message, as shown in Figure 5-3.
page 170
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 171
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-4: If mistakes are encountered in the coding or DTD, the errors are listed.
<!DOCTYPE eFolks [
]>
<eFolks>
<contact>
<name>Bill Sanders</name>
page 172
Server-Side Flash: Scripts, Databases, and Dynamic Development
<email>[email protected]</email>
</contact>
<contact>
<name>Mark Winstanley</name>
<email>[email protected]</email>
</contact>
<contact>
<name>Betty Boop</name>
<email>[email protected]</email>
</contact>
</eFolks>
In this example, the first !ELEMENT definition is of the root element, eFolks, which is defined in terms
of the contact element. Because the root element contains more than one contact element, the
description of the data must include a plus (+) sign after it. So the data type definition for the root
element is (contact+).
The next element is contact, and all the contact elements contain one name element and one
email element. To order the data in an XML file when defining the data, place a comma (,) between
each of the elements in the definition. (If it doesn’t matter which order they’re in, use the vertical bar (|)
or pipe character to separate elements in the definition.) Because we want the person’s name to come
before the e-mail address, we wrote the definition as (name,email). You may wonder why we didn’t
place a plus (+) sign after each of the two elements because the document clearly has more than a
single element of both. If you look between the <eFolks> and </eFolks> tags, you see more than
one <contact> tag. However, if you look between the <contact> and </contact> tags, only a
single instance of both the name and email elements appear. All that’s left to do is to define the name
and email elements. Because they contain no other elements, and they do contain character data,
both are defined using (#PCDATA).
After you finish, save the document as contacts.xml and use a validation program to make certain
that the document is well formed. After you validate the contacts. xml document, put it in the
directory where you create the Flash movies for this book. It serves as the basis for your initial Flash
movie that brings in XML.
page 173
Server-Side Flash: Scripts, Databases, and Dynamic Development
Background layer
Follow these steps to create the Background layer:
1. Choose Modify → Movie and change the background color to black.
2. Draw a dark gold (#FFCC00) rectangle in the middle of the stage with the
dimensions W=320, H=205.
3. Above the rectangle, use the Text tool to type XML Database and position the
text above the rectangle, as shown in Figure 5-5. Use a 16-point bold Verdana
text in the same dark gold color as the rectangle.
page 174
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-5: Most of the work to set up the movie is in creating the ActionScript.
4. Select the rectangle and then press down the Shift key and press the up arrow
key four times and the left arrow key four times to provide the correct offset from
the center where the text field is to be positioned.
ActionScript layer
Now that your movie’s structure is established, you’re ready to add the ActionScript that brings the XML
data into your Flash movie. Click the first frame in the ActionScript layer and right-click the mouse
(Cmd+click on the Macintosh) and choose Action. After the Frame Actions panel opens, type the
following script in the ActionScript editor. (You’re likely to find using the Expert mode for this script
easier. Press Ctrl+E/Cmd+E to enter the Expert mode in the Frame Actions window.)
contactXML = new XML();
contactXML.onLoad = transXML;
display = "Getting XML.";
contactXML.load("contacts.xml");
function transXML () {
if (this.loaded) {
page 175
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-6: The data on-screen reflects the data in the XML document.
page 176
Server-Side Flash: Scripts, Databases, and Dynamic Development
The first line employs the XML constructor object. With the constructor object, you provide an
object for the XML document you are loading:
contactXML = new XML();
We used a name for the object that related to the XML data and document rather than using a more
generic name.
If you have a big XML document, you may want to give the user something to look at while waiting for
the data. By assigning a loading message, as in the following example, you let the user know that the
job is under way:
display = "Getting XML.";
Next, you specify the XML file from which you plan to extract the data. The XML load method requires
only the file’s URL. (Because we always put the XML documents in the same folder/directory as the
SWF file, we have short URLs.)
contactXML.load("contacts.xml");
After the loading process begins, you fire the function that is initiated by the onLoad method.
Usually, the viewer doesn’t see that message very long because as soon as it arrives, the text field is
filled with the XML data. But you can easily create a special text field to place the messages about the
loading of the data and have a separate text field for the data itself. With larger files, a message field
can serve both for error-checking and giving the viewer something to assure him that the data is loaded.
Two more objects need to be declared: an object for the root node and an array that collects all the
data. We used the label keyTag for the root node label and contactList for the array within the root
node, as follows:
keyTag = new XML();
contactList = new Array();
To find the root node, you just use the last child’s node name. The closing tag’s element name is the
same as the root element’s opening tag and so is considered the “last child.” (To check this out,
comment out the loop by using double slashes in this next section and type
display=keyTag.nodeName;. The text field displays eFolks, the root node.) Declare the keyTag
variable as the root directory.
keyTag = this.lastChild;
Now that you have the root node in a variable, you can define the child nodes of the root node as an
array. While you’re at it, you may as well clear the display text field:
contactList = keyTag.childNodes;
display = "";
page 177
Server-Side Flash: Scripts, Databases, and Dynamic Development
Finally, you want to get the elements out of the array contactList. Use a loop to go through the
array. The counter named kid is used to remind you that the two elements that make up the contact
element are its child nodes, as follows:
for (kid=1; kid<=contactList.length; kid += 2) {
display += contactList[kid];
}
}
<!DOCTYPE eFolks [
On the Flash side of the equation, the only change you must make is to the name of the XML file that
Flash loads. So you need to change the following line:
contactXML.load("contacts.xml");
page 178
Server-Side Flash: Scripts, Databases, and Dynamic Development
Choose File → Save As and save the new movie as contactPh.fla. Figure 5-7 shows that an entire
new field is now added in this movie.
Figure 5-7: When you add a field (new element) to the XML file, the data in the new field can appear in
Flash with no new additions to the ActionScript other than changing the name of the XML file to load.
contactXML.onLoad = transXML;
contactXML.load("contacts.xml");
page 179
Server-Side Flash: Scripts, Databases, and Dynamic Development
function transXML () {
if (this.loaded) {
keyTag = this.lastChild;
contactList = keyTag.childNodes;
display = "";
if (contactList[kid].nodeName.toLowerCase() == "contact") {
nameList = contactList[kid].childNodes;
nodeID = nameList[nl];
elementID = nodeID.nodeName.toLowerCase();
if (elementID == "name") {
name = nodeID.firstChild.nodeValue;
if (elementID == "email") {
email = nodeID.firstChild.nodeValue;
}
In the previous section, the loop through the root’s first child (<contact>) created an array for all the
XML data, and because the data were well formed, outputting them to the text field (display) was
simple. But to break up the elements that make up the contact element requires an array made up of
the contact element. So the first order of business is to find the contact element using a loop
through the big array called contactList, as follows:
for (kid=0; kid<=contactList.length; kid++) {
page 180
Server-Side Flash: Scripts, Databases, and Dynamic Development
if (contactList[kid].nodeName.toLowerCase() == "contact") {
As soon as the contact node is located, the nameList array is defined as the child nodes of the child
nodes of the element of the array where the node name was identified. In other words, when an array
element is identified, it is an array with its own elements. This can be confusing because XML elements
refer to data within a tag container and array elements refer to elements of the array. (Remember from
the XML document that the contact element is defined in terms of the name and email elements, so
the contact element is indeed the parent node of the two child nodes, name and email, and the array
extracts those child nodes of the contact element — or grandchildren of the root element.)
nameList = contactList[kid].childNodes;
After the array is identified, the script uses a loop to search the array for the name and email child
nodes. The nodeID is an XML object used to capture the XML data. Then elementID becomes the
variable name for the node name, as follows:
for (nl=0; nl<=nameList.length; nl++) {
nodeID = nameList[nl];
elementID = nodeID.nodeName.toLowerCase();
Next, the script checks to see whether the element is labeled "name" or "email". If it is the former,
the data are placed into the name variable, and if it is the latter, the data go into the email variable:
if (elementID == "name") {
name = nodeID.firstChild.nodeValue;
}
if (elementID == "email") {
email = nodeID.firstChild.nodeValue;
}
All that’s left to do is to put the (now separate) datum into the output window in Flash. In creating your
output, use caution in placing it among all of the closing curly braces generated by the multiple loops
and the conditional statement, not to mention the big function, as follows:
}
display += name+" = "+email+newline;
}
}
}
Figure 5-8 shows what you now see with the reformatted data from the XML file.
page 181
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-8: After the individual data elements are separated from the XML file, the ActionScript can
rearrange their output.
page 182
Server-Side Flash: Scripts, Databases, and Dynamic Development
same record (sibling set). In the Flash 5 movie project for this section, the name element is used to
search for the associated email element.
This movie begins with a new stage and two different text fields and a button to launch a search. Open
a new movie and enter the following five layers:
Background
Search Field
Found Field
Button
ActionScript
Save the movie as SearchMe.fla and then add the colors in Table 5-2 to the Swatches panel.
Table 5-2: Color Palette for SearchMe.fla
page 183
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-9: One text field provides the search variable and the other provides the match variable.
Background layer
Use the tan from the color palette for the background color and follow this next set of steps for creating
the labels and backdrops:
1.Use the Rectangle tool to create a rectangle measuring W=325, H=70. Use the red
(Color C) for the stroke and fill colors. Copy the first rectangle and paste it below
and to the right of the first one, using Figure 5-9 as a guide.
2.Set the Stroke value to 10 and, with a black stroke and white fill, draw a second set of
rectangles on top of the first two, as shown in Figure 5-9. For easier management,
select each set of rectangles and group them by first selecting them and then
pressing Ctrl+G or Cmd+G.
3.Add a rectangle at the top, using the blue stroke color with no fill, and type the label
XML Search. Add Name and Email labels on the rectangle backdrops, as shown
in Figure 5-9. Finally, add the Click to find email address below where the button
is to be placed.
page 184
Server-Side Flash: Scripts, Databases, and Dynamic Development
bold font with the red from the movie’s palette. Finally, in the Variable window, type
search.
2.Place a second text field over the bottom backdrop rectangle. Make the second field
a dynamic text field in the same dimensions of the first and leave all boxes,
including Border/Bg, unselected. Type found as the variable name.
Button layer
Use the Oval tool to draw a circle with a white fill and blue stroke. Create a button symbol by selecting
the drawing, pressing the F8 key, and choosing Button as the behavior. Save the symbol as Seek. Add
the following ActionScript:
on (release) {
gotoAndPlay (2);
}
All the script does is release the stop action in the first frame so that the big script in the second frame
can launch.
ActionScript layer
The two action scripts in this layer constitute the heart of the movie. The script in Frame 1 is pretty
simple. It focuses the cursor in the top text field and stops the movie. The purpose of focusing the
cursor is to immediately guide the user to the correct field.
Selection.setFocus("_root.search");
stop ();
The next script is placed in the second frame. Notice that the first part of the script is similar to the
scripts in the previous two Flash movies that use XML. But more arrays and variables are added so that
the code can match one array element with another and output the results in another text field (see
Listing 5-4).
Listing 5-4: ActionScript for Frame 2 of SearchMe.fla
contactXML.onLoad = transXML;
contactXML.load("contacts.xml");
function transXML () {
if (this.loaded) {
Nseek = 0;
page 185
Server-Side Flash: Scripts, Databases, and Dynamic Development
Eseek = 0;
flag = 0;
keyTag = this.lastChild;
contactList = keyTag.childNodes;
if (contactList[kid].nodeName.toLowerCase() == "contact") {
nameList = contactList[kid].childNodes;
nodeID = nameList[nl];
elementID = nodeID.nodeName.toLowerCase();
if (elementID == "name") {
name[Nseek] = nodeID.firstChild.nodeValue;
if (name[Nseek] == search) {
flag = 1;
Nseek += 1;
if (elementID == "email") {
email[Eseek] = nodeID.firstChild.nodeValue;
if (flag == 1) {
found = email[Eseek];
flag = 0;
Eseek += 1;
page 186
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 187
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 5-10: If the name you enter matches the name in the XML document, Flash displays the e-mail
address associated with the name.
Another Flash innovation that is ahead of the curve is the XML Socket objects. Without a stable socket
server for these Flash objects, using — and certainly writing about — XML sockets is a bit dicey. Still,
XML Socket objects are important innovations. They enable a rapidly changing movie to receive data
almost instantaneously through an open socket to a data source. In this way, a game or other Flash
application can have rapid and complex interactive objects without needing to load all the data first. New
and updated data available over the Internet can readily flow into and out of Flash in real time. So,
although Flash can do a good deal with XML documents, far more integration with Flash and XML is on
the near horizon.
page 188
Server-Side Flash: Scripts, Databases, and Dynamic Development
Summary
This chapter shows that using Flash’s XML objects with ActionScript can pull data out of an XML
document. What’s more, when the XML data is extracted, Flash makes a great front-end for displaying
the data. By thinking of XML as a many- tiered array or tree, you can go deep into the rich data
formatting capabilities of XML and display them in the equally rich display formatting tools in Flash.
After you pull data out of an XML file, you may want to think about printing it out for hardcopy
distribution. Chapter 6 shows how to format and print data using Flash. Although Flash is primarily a tool
for displaying data on the Web, it can also be used to send data from Flash to a printer. If you want your
XML data handed out at the next board meeting, see the next chapter to find out how to make it look
good.
Printing Basics
Before you can learn what ActionScript code to use to target a user’s printer for massive paper
consumption, you need to review a few basic printing matters, such as fonts and graphic formats.
Fonts in Flash
When creating text fields in Flash, you first use Flash’s Text tool to place your text field on the stage.
Using the Text Options panel (shown in Figure 6-1), you then configure the field to be Static, Dynamic,
or Input. The Dynamic and Input menu options enable you to embed font sets within your Flash movie.
Figure 6-1: You choose fonts for your text fields in the Text Options panel.
By clicking the buttons at the bottom of the panel, you can specify to include either the entire font set or
only certain characters of the font you’re using when you export your Flash movie. Including the font set
enables those people who don’t have the font you’re using installed on their computer to still be able to
view it. This feature is important to keep in mind when you are configuring text content in Flash for the
possibility of being printed out. If the text is in a dynamic text field, make sure that you export the font
with field. Exporting the font makes the Flash SWF file somewhat larger, but at least people can see
your fonts.
When you include Static (nondynamic) text in your Flash movie, do either of the following tasks in order
to make sure people can view your chosen fonts correctly:
Break the text all apart using Ctrl+B. This task is very time-consuming and prevents you
from going back and editing your text later.
Convert text blocks into Graphic symbols and then place those onto the stage. Flash
then exports the text blocks as graphics and not as text in a font that no one can see.
After you’ve made sure that you have you’re fonts configured correctly, you can be assured that anyone
viewing your Flash movie will be able to see them and print them as well.
page 189
Server-Side Flash: Scripts, Databases, and Dynamic Development
Flash uses primarily vector graphics to ensure small file sizes and easy replication on most anyone’s
computer. Often times, though, you might like to include bitmaps. As you’ll notice in Flash, when you
scale a bitmap image that you’ve imported to a larger size, the image becomes quite pixilated. Printing
in Flash often causes objects that are small on the stage to be enlarged to a very large size on the page
you’re printing them on, revealing a lot of pixilation.
To prevent this pixilation, you can either avoid using bitmaps altogether when you know you’ll be
printing something from Flash or use a higher quality bitmap image file so that it won’t look so pixilated
when it scales up to the size of an 8.5 by 11 page. Using high-quality bitmaps will add to the size of your
Flash movie just like embedding your fonts will, but it’s a good way to ensure higher quality prints, if
that’s what you’re after.
Flash prints vector graphics very smoothly and scales them nicely on a PostScript-enabled printer, and
just about every printer sold today has PostScript capability. If by chance someone viewing your
printable Flash movie doesn’t have a PostScript-enabled printer, he or she will still be able to print your
Flash content, but it will be converted to a bitmap image first and then sent to the printer. The resulting
output will be at a lower quality than if the viewer were using a PostScript printer. Unfortunately, there’s
no way to prevent this. If the document must look right everywhere and anywhere it’s to be printed and
seen, you may want to check the quality of anything you’re designating as printable in Flash by printing
it on both PostScript and non-PostScript printers.
Note When a PostScript-enabled printer is detected, all the content in Flash that’s
being printed is first converted to PostScript and then sent to the printer. This
conversion can result in a temporary file size that is much larger than what the
size of the actual SWF file is and may possibly load down a network of printers or
an intranet if the file size happens to be ludicrously huge. You can check this file
size by exporting any frames in Flash that you want to print into an EPS format.
The total size of these EPS files determines the file size that a viewer’s computer
will send to the viewer’s printer or network.
The advantages of printing from Flash are many! Flash has the unique capability to not only print what
is viewable on the stage, but also to print frames in a movie clip that is completely hidden. Common
uses for Flash printing include the following:
Printing a multipage document from a banner ad that is very small by hiding a movie clip
that contains all your printable frames on the stage with its visibility set to 0
Providing security for Flash movie content by specifying which frames are printable and
thereby preventing the user from choosing the Print command in the context menu of
the plug-in itself and printing frames that you haven’t specified
Creating games where players can print out statistics on how well they played after they
finish the game. (The game itself can even be related to printing: the object of the game
could be to design a unique layout in Flash and print the results when you’re done.)
Providing printed hard copy receipts for purchases made by customers on an e-
commerce site that uses Flash
Providing scalable graphics, such as maps or blueprints, and letting the user choose
how big or small to scale them and print them out
Providing some show-stopping graphics that look so cool that people want to hang them
on their walls
You could probably dream up hundreds of uses for letting users print out content from a Flash movie
you create. When you see all of the available options, it may spur you to change the way you build your
Flash movies and structure them so they are easily printable.
page 190
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 6-2: If you have five frames you’re printing from Flash, you’ll have five pages coming out of your
printer, with one frame per page.
Normally, you’ll execute the print action from a button, but you can also attach it to a frame action or
clip event because users will still have to confirm printing options in their computers’ normal Print dialog
box that pops up. But if users see this dialog box just pop up of out of nowhere, they may be confused,
so from a usability standpoint, attaching the print action to a button the user can click is the best way
to go.
page 191
Server-Side Flash: Scripts, Databases, and Dynamic Development
warning, duplicate frame labels are perfectly okay as long as the duplicates
are all #P labels. (This warning is an oversight on the part of Macromedia; it
would probably take only a few lines of code in the Flash architecture to make
it ignore #P frame labels.)
Flash scans through the timeline specified by the target parameter of the print action and extracts
only those frames labeled #P for the purpose of sending them off to the printer. When it finds one of
these frames, it exports everything visible on the stage in that frame across all timeline layers to the
printer. If Flash can’t find any frames labeled #P, it will begin at Frame 1 of the target timeline and print
each and every frame after that until it reaches the last frame of that timeline.
Note All the testing for #P frame labels and converting the frames to a printable format
happens in the background, and users never see anything transpiring visually in
the Flash movie. Users do see their usual Print dialog box popping up and asking
them to choose their printer and print options. This result is no different than if
they had tried to print a page from a word processor, a spreadsheet, or a graphics
program.
Another important point to note is that you need to decide in advance which frames in your target movie
clips and timelines are the ones that you’re going to want to print. Because Flash is depending on frame
labels to tell it which frames are printable, and you can’t create frame labels dynamically once you’ve
exported your movie, some planning is required when you are creating a movie if you need to specify
certain frames as printable.
Tip The #P labels can be attached to keyframes only, so you’ll need to account for this
if you have tweened sequences in your timeline or movie clips. The best way to
deal with this issue is to add a layer on top of all your existing timeline layers that
contains only blank keyframes with the #P labels used to designate those frames
as printable. Having this layer enables you to print stills from the middle of tweened
sequences. Figure 6-3 shows what this layer may look like.
page 192
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 6-3: A separate layer has been created to designate printable frames in this movie clip, which
contains tweened animation. This layer prevents having to add unnecessary keyframes in the middle of your
motion tweens.
page 193
Server-Side Flash: Scripts, Databases, and Dynamic Development
frame in the target movie clip or timeline, Flash will become confused, and you probably won’t get the
cropping you desire. Let’s take a look at how the bmovie parameter works in a real-world application:
On the CD- This next example uses the bmovie.fla file found on the CD-ROM. This
ROM Flash movie has five frames that contain graphics created by Nate
Yarrington of entertainovision.com. Copy this file to your local hard drive
and then open it in Flash for the purpose of editing it.
1. Scroll through the five frames in bmovie.fla to get an idea of the pictures they
contain. Each frame has a large vector graphic in the center of the stage with
smaller scale versions of the same graphic around it.
2. Create a new timeline layer above the existing Graphics layer and name it Print
Parameters.
3. The new Print Parameters layer should already have a blank keyframe at Frame
1. Create two more blank keyframes at Frames 2 and 5.
4. Give Frames 1, 2, and 5 each the frame label #P by using the Frame panel. This
step creates duplicate frame labels, but this duplication is okay. You are telling
Flash that these are the only frames that it is allowed to print on this timeline.
5. Return to Frame 1 and attach a stop(); frame action to it to keep Flash from
playing through all these frames when you test the movie.
6. In Frame 1 of the Print Parameter layer, create a button on the stage or drag one
from Window → Common Library → Buttons and place it in the upper left corner
of the stage. Use static text next to this button to label it PRINT.
7. Attach the following code to the button you just created:
8. on (release) {
9. printNum (0, "bmovie");
10. }
Now the movie is set up to print Frames 1, 2, and 5 in Level 0 that you’ve specified for printing with the
frame label #P. You’ve specified bmovie as your bounding box area parameter, so Flash will look for a
frame labeled #b to find out what segment of Frames 1, 2, and 5 to print. The next step is to create this
bounding box area:
1. Create a blank keyframe at Frame 10 in the Print Parameters layer and attach
the #b frame label to it by using the Frame panel.
2. With Frame 10 in the Print Parameters layer selected, use the Rectangle tool
with a fill and stroke color of black to create a square in the center of the stage
measuring approximately 150 x 150 pixels. The Info panel can assist you in
setting this exact size, and the Alignment panel can help you center it to the
stage.
3. Use the onion skinning feature in the visual layout of the timeline to view all the
frames at once and you’ll see that the black 150 by 150 square covers only the
center object in each frame. In many cases, the images are slightly bigger than
the square, but this size difference is okay, because you’ll be seeing how this
square will crop these images.
This black square is now the area of the stage that will determine the cropped printing area for any
frames marked with #P, because the black square is in a frame that you have designated #b for the
bmovie bounding box area. Keep in mind that once Flash extracts the designated area from each of
the #P frames, it will then scale the cropped images to fill each printed page. Figure 6-4 shows the final
layout of the timeline. (The completed file is available on the CD-ROM as bmovie_complete.fla if
you’re experiencing any difficulties laying out the timeline.)
page 194
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 6-4: The completed layout of the timeline for the bmovie.fla file with Frames 1, 2, and 5 designated
for printing and Frame 10 designated as the bounding box area.
Test the movie in Flash or in your Web browser. It should stop on Frame 1 and show a little montage of
the universe. Click the button you created, and your computer’s Print dialog box should appear. Choose
the correct options for your computer and designated printer and then start printing!
Only three pages should come out of your printer, one for each frame specified by your #P labels, which
in this case are Frames 1, 2, and 5. Because we used the bmovie bounding parameter in the print
action along with the #b frame label on Frame 10 containing the 150 by 150 black square, you should
see only that 150 by 150 area from the stage containing the center object in each frame. But after
cropping to this 150 by 150 area, Flash then blows up the image to fill the entire printed page, so you’ll
see a giant flower, house, and tree come out of your printer.
Some of the images might have been cropped too much. Try returning to the Flash movie and changing
the size of that 150 by 150 black square in Frame 10 to a bigger size that totally encompasses the
center images in Frames 1, 2, and 5. The onion skinning feature on the timeline can assist you with this
adjustment. Test your movie and print it again. Notice that the print area for all the frames changes with
the size of the black square. Now all those center images should print without any of their sides, tops, or
bottoms missing.
Try specifying more or fewer frames as printable by adding or removing #P frame labels. You’ll find that
the number of pages printed increases or decreases accordingly. Finally, try making more than one
black square in Frame 10 or even using multiple circles and complex shapes in a variety of colors. You’ll
see that the bounding box that surrounds all the elements in Frame 10 is what is used to designate the
bounding area for the #P frames.
Note The elements in the frame you label #b do not create a mask for the printable
frames in and of themselves. Instead, the square area that encompasses all the
page 195
Server-Side Flash: Scripts, Databases, and Dynamic Development
elements in the #b frame is what basically masks the printable frames. A quick
way to see this area is to convert any elements in the #b frame into a symbol so
that when you select the symbol, a square bounding box appears around it.
Suppose you wanted a more accurate representation of all the objects in every frame you’ve labeled #P
to be printed out. You want to see everything that’s on the stage in each of those frames. To accomplish
this, change the size of the black square in Frame 10 to 550 by 400 pixels and center it to the stage.
Test the movie and view the printout. Every object in every frame labeled #P should print out to each
page. If printing every object in every frame is your goal, though, using bmovie makes for extra steps in
the process. The bmovie parameter is useful for when you want to print out an area smaller than the
area encompassing all the objects in each frame. To print the area encompassing all the objects in each
printable frame, use the bmax parameter.
Tip In many of the examples, you’ll probably notice that the button that you’re clicking
to print is showing up in your printouts. To correct this problem, move all the frames
containing any images to a frame other than the one containing the button. As long
as the frames you want to print are marked with the #P label, Flash will find them
and print them. Another solution is to put all the frames you want to print in a
separate movie clip and then use the target parameter of the print action to
specify that movie clip.
page 196
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 6-5: The approximate look of three pages printed with the bmax parameter where all the objects in
the printable frames are viewable on the printed pages at an accurate relative scale.
Herein lies the power in designating bmax as your bounding box parameter. It is the quickest and
simplest way to ensure that every object in every frame you’ve designated as printable makes it onto
the printed page, and every frame that’s printed has a relative scale. If you’re printing out only one
frame in your designated target timeline, bmax is usually the option you’ll most often want to choose,
unless you need the cropping power of bmovie.
Tip The bmax bounding box parameter is the best way to get an accurate scale
representation across multiple printed frames. Objects inside Flash that look small
in one frame, in comparison to objects that look big in another frame, retain these
ratios when you use the bmax parameter in your print action.
What if you want to ensure that every object in every frame makes it to the printed page but that all
those objects are scaled to fill the printed page on a frame-by-frame basis? Keep this file you’ve just
worked on handy and move on to the final bounding box parameter, bframe, to find the answer.
page 197
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 6-6: The layout of the stage containing the four smaller trees moved in very close
next to the center tree.
4. Test the movie and view the printout. You should see that the page printed with
the trees on it corresponds in scale to the other two printed pages. In other
words, the scale has not changed, you’ve just changed the position of the
smaller trees.
5. Return to Flash and change the ActionScript attached to the Print button in
Frame 1 of the Print Parameters layer to the following:
6. on (release) {
7. printNum (0, "bframe");
}
You have just configured the print action to print out all the frames using the bframe
bounding box parameter.
8. Test the movie and click the Print button to print out the designated frames. (If
you encounter any problems, this file is available on the CD-ROM as
bframe_complete.fla.)
When viewing the printout, look at the page with the trees that you moved in toward the center. You
should have a giant set of trees that fills the whole page! This size change occurs because when Flash
was exporting to the printer, it went frame by frame through each of the frames designated as printable
with #P and looked at the maximum area for each of those frames. Flash then scaled each frame to fit
the page. Because the other two frames that were printed (Frames 1 and 2) contained objects spread
out over a great distance all the way to the edges of the stage, Flash had to maintain the relative
positioning and printed them out much the same as they were printed when Flash was using the bmax
parameter. When Flash reached the frame containing the trees, it found all the objects tightly grouped in
a small area. Flash then had a much smaller bounding box area around all the objects in that frame and
scaled up that entire area to fill the printed page.
The bframe parameter of the print statement is useful when you have multiple frames to print and
you want the bounding box for each frame to be determined on a frame-by-frame basis instead of being
an average of all the printable frames. So if you have many frames to print that contain different object
layouts (some tightly grouped and some spread apart) and you want them to all appear as big as
page 198
Server-Side Flash: Scripts, Databases, and Dynamic Development
possible on the printed page without any regards to large scaling differences between pages, use the
bframe parameter.
Note When using the bmax and bframe parameters, you do not need to add any
special extra frames to the Flash movie. In contrast, you have to add a #b frame
label to a frame to designate the bounding box area when using the bmovie
parameter. In fact, even though the frame containing the #b label and the black
150 by 150 square was removed in one of the examples, this step wasn’t
necessary. When the bmax or bframe parameter is used, Flash determines the
bounding box area on its own and completely ignores any frame with a #b frame
label.
page 199
Server-Side Flash: Scripts, Databases, and Dynamic Development
You should have two pages coming out of your printer corresponding to the two frames you designated
with #P: one contains a futuristic-looking ballerina and the other contains an evil pumpkin. Depending
on the speed of your computer, it may take a little time for Flash to compile and print these pages. This
brief period, however, pales in comparison to the time it would take for Flash to print these frames using
the standard print action.
Caution You may be tempted to try and print these two frames (or more) out of
printAsBitmap.fla using the standard print action instead of the printAsBitmap
action just to see how much longer it takes. If you want to do this comparison,
save all your important work and close any other open programs. Your
computer may freeze or crash. The difference is worth experiencing, but be
prepared to call up whatever command you need to quit a hanging program
when and if Flash hangs trying to export these images. Try designating all the
frames as printable to really see the difference in speed!
The reason for the delay if you’ve tried using standard print here is that, as mentioned earlier in the
chapter, Flash is trying to convert everything into a vectorized PostScript format and there’s just too
much data to work with. Rather than having Flash trying to perform all that math on the pictures and
hanging up a user’s computer or network as a result, it’s more efficient to just deal with images as
bitmaps and sacrifice a little bit of quality in some instances for the speedier printout or just the
capability to print the images at all!
The best way to figure out when and if you need printAsBitmap is to start with just the standard
print action and test the effects on your own computer and the computers of some friends you enlist
to help you. Always warn them of the possibility of their system hanging, however! If the standard
print action is speedy and produces the desired quality of output, stick with it. If getting anything to the
printer seems like it takes forever, switch to printAsBitmap and see whether you can live with the
image quality reduction, if any. Many times you’ll find that switching to printAsBitmap doesn’t seem
to effect to your image quality at all.
To demonstrate these amazing features in detail, this section presents two projects. The first project
focuses on printing frames from a tweened sequence inside a movie clip that isn’t visible. The second
project focuses on printing hidden dynamic text fields and printing frames from an SWF file that you’ve
loaded into Flash.
page 200
Server-Side Flash: Scripts, Databases, and Dynamic Development
3. Using the Info panel, resize the flower to be 125 pixels high by 110 pixels wide.
Position it at x-coordinate -210 and y-coordinate 0.
4. Create another keyframe in the Flower layer at Frame 20 by selecting Frame 20 and
pressing F6 to create a duplicate of Frame 2. Reposition the flower in Frame 20 at x-
coordinate 210 and y-coordinate 0.
5. Select any frame in between Frames 2 and 20 in the Flowers layer and create a
motion tween with Insert → Create Motion Tween.
6. Create another layer above the Flower layer in the Moving Images timeline and name
this layer Silhouette. Create a blank keyframe in Frame 2 of this layer and drag the
Silhouette symbol from the Library into Frame 2, resizing it to 150 pixels wide by 125
pixels high. Position it at x-coordinate 0 and y-coordinate -170.
7. Create a keyframe in Frame 20 of the Silhouette layer by pressing F6 and creating a
duplicate of Frame 2. Position the Silhouette graphic in Frame 20 at x-coordinate 0
and y-coordinate 170.
8. Select any frame in the Silhouette layer between Frames 2 and 20 and create a
motion tween by choosing Insert → Create Motion Tween. Move the Flash playhead
along the timeline to get an idea of how the images on the stage move relative to
each other.
9. Create another layer in the timeline and label it Print Parameters. Create blank
keyframes in Frames 2, 14, and 20 of this layer. Label each of these three keyframes
with the #P frame label.
10. Place a stop(); frame action in Frame 1 of the Print Parameters layer. Figure 6-7
shows the complete layout of the timeline for the Moving Images movie clip.
Figure 6-7: The layout of the layers and objects in the timeline of the Moving Images movie
clip.
11. Return to the main timeline of the movie where the Print button resides. Create a new
layer in this timeline and name it Target. Select Frame 1 of the Target layer and drag
the Moving Images movie clip symbol from the Library to the stage.
12. Because Frame 1 of the Moving Images clip is blank, you’ll see only a small dot on
the stage as a place marker for this movie clip. Position it wherever you’d like, and
with it selected, give it an instance name of movingImages in the Instance panel.
13. Select the Print button in the Button layer and attach this ActionScript:
page 201
Server-Side Flash: Scripts, Databases, and Dynamic Development
14. on (release) {
15. print ("_root.movingImages", "bmax");
}
16. Test the movie in Flash or in your browser and click the Print button. If you encounter
any difficulties, the complete file is available on the CD-ROM as tween_complete.fla.
Three pages should come out of your printer, each representing a frame in the timeline of the Moving
Images movie clip. The first page shows the flower and silhouette graphics at their start positions while
the second page shows them just after they cross, and the final page shows the graphics at their ending
positions. You have just printed frames pulled from a tweened sequence that was inside a movie clip
that was completely invisible to the user!
Notice that Flash used the inside of the _root.movingImages movie clip as the reference for where
to place the elements on the printed pages. The bmax parameter made Flash look at all the frames in
that movie clip and created a bounding box area to depict the graphics across the full length of their
travels. It didn’t matter where on the main timeline you placed the clip, as long as you gave it the same
instance name you referenced in the code for the Print button.
Note Try changing the bmax parameter on the Print button to bframe. You’ll see that as
the graphic objects move closer together they appear larger on the printed pages.
Because the objects are contained in a smaller area when they are closer
together, Flash scales them up to fit the page because bframe operates on a
frame-by-frame bounding box basis.
Even though we created the Moving Images movie clip to have a blank first frame, you could easily
delete that first frame. Of course, doing so would make the movie clip completely visible on the main
timeline; to make the movie clip invisible, you could add the following clip event ActionScript to it:
onClipEvent(load)
this._visible=0;
}
This ActionScript would render the movie clip invisible the moment it loads. However, through the
unique power of the print action, Flash would still print the frames you designated for printing inside
the Moving Images movie clip.
Tip Using the method described here you could easily produce a large brochure printed
from a small Flash movie measuring the size of a banner ad or smaller. Create a
movie clip whose frames contain all the pages of your brochure and either leave
the first frame blank or use the movie clip’s _visible property to render it unseen.
If you name the instance and target it properly in the print action (along with the
proper bounding box option), a large brochure will magically appear from the user’s
printer even though the Flash movie he or she is viewing is very small.
Printing an invoice/receipt
Flash’s print action has a few more surprises left to reveal. In this project, you build an invoice/receipt-
generating Flash movie that pulls dynamic data to be printed from a completely different area of the
Flash movie than the one being printed. You also explore Flash’s capability to load in an external SWF
file, fill it with data, and print it out.
page 202
Server-Side Flash: Scripts, Databases, and Dynamic Development
create. Make sure the Border/Bg check box is checked for each field you create,
and they should all be Single Line, Input Text fields, unless otherwise noted. All
text fields for the rest of this project utilize 18-point Times New Roman black.
Figure 6-8: The layout of the Invoice movie clip inside of receipt.fla.
8.In Frame 2, just inside your border, create a single-line, dynamic text field. Specify
_root.clientName as the variable and leave the Border/Bg check box unchecked.
page 203
Server-Side Flash: Scripts, Databases, and Dynamic Development
Position the field near the top left of the layout at approximately x-coordinate -143
and y-coordinate -112. This text field should be about 165 pixels wide and 25 pixels
high.
9.Directly below this text field, create two more: one that is a multiline dynamic text field
with a variable reference of _root.clientAddress and the other a single-line dynamic
text field with a variable reference of _root.clientPhone. Leave the Border/Bg check
box unchecked for both fields.
10. Further down within the border, create a single-line dynamic text field that is
approximately 430 pixels wide and 40 pixels high. Give this field the variable
reference _root.message and position it so that it’s centered in the layout.
11. At the very bottom of your virtual invoice, use some static text to place the words
TOTAL: $ on the stage. Next to these words, place a dynamic text field with the
variable reference _root.total that is approximately 130 pixels wide. Use Figure 6-8
as a guide. (The completed file is available on the CD-ROM as
receipt_complete.fla.)
12. Return to the main timeline where you originally placed all the input text fields. Add
a layer to the timeline and name it Invisible Invoice. Select Frame 1 of this layer
and drag the Invoice movie clip you just created from the Library and place it on the
stage. Because Frame 1 of this clip is empty, you’ll see only a little dot on the stage
to signify where the clip is located.
13. Place the Invoice movie clip anywhere on the stage you’d like. Select the clip and
give it an instance name of invoice in the Instance panel.
14. In the Input Area layer, select the Create Invoice button and attach the following
ActionScript to it:
15. on (release) {
16. total=Number(mowingServices)+Number(otherServices)+
17. Number(rawMaterials);
18. message="Thank You very much "+clientName+"! Have a
19. nice day!";
20. print ("_root.invoice", "bmax");
}
Test the movie in Flash or inside your browser. Enter any contact information you’d like along with any
dollar values for services. Click the Create Invoice button and view the printout. You’ll notice that all the
values you entered for your contact information have been correctly output in a new layout with a
special message to you and the total dollar value of all the values you entered. Again, if you need any
help, the completed file is available on the CD-ROM as receipt_complete.fla.
How exactly does this invoice work? As you typed data into the input text fields present on the main
timeline, the corresponding values were set and stored right there in the _root. The dynamic contact
information fields in the invoice movie clip then pulled out these values by directly referencing them
on the _root. The remaining two variables output in the invoice, message and total, are created
when you click the button to create the invoice.
The total variable is just a total of all the dollar values you entered into the input fields on the main
timeline (all input data is now treated by Flash as strings, so the values had to be converted with
Number() first). The message variable is just a text message with the clientName variable
concatenated into the middle. These variables are set and held in the main timeline when you click the
Create Invoice button. The text fields in the Invoice movie clip pull these values by referencing them
directly on the _root, like with _root.total for the total field.
The magic here is the capability to print frames inside an invisible movie clip that contains dynamic text
fields. This capability means that you can generate custom invoices, receipts, and reports based on
data entered by the user. You can even customize the documents with the user’s name or other unique
information!
Tip Leaving the Border/Bg check box unchecked when printing dynamic data is a great
way to make the documents you print look fully customized and dynamic. If you
leave the backgrounds in, Flash prints them, and they look rather blocky and form-
like. People expecting a customized printed document will appreciate the fluid
integration and slick look of text without blocks around it!
page 204
Server-Side Flash: Scripts, Databases, and Dynamic Development
In the last project, we showed how printable frames inside a hidden movie clip can print data from the
main timeline just by placing the correct path and variable reference in the Text Options panel for those
text fields. In this example, we use the same basic file from the last example, but we modify it to load a
receipt template from an external SWF file.
On the CD- For this example, you’ll need the CD-ROM files template_receipt.fla and
ROM receipt_complete.fla (or use the file you completed in the last example).
Transfer both of these files to the same directory on your local hard drive.
Take a look at the file receipt_complete.fla if you’re unfamiliar with it from the last example. It
contains input text fields on the main timeline. A button at the bottom of the stage then prints out a
frame from a hidden movie clip on the main timeline that has an instance name of invoice. Dynamic
text fields inside of the invoice movie clip reference the variable values on the main timeline and print
out the corresponding data.
Notice that the file template_receipt.fla has a very small stage size because the only thing on the
stage is a replica of the Invoice movie clip from receipt_complete. fla with a few minor changes.
Double-click on this movie clip inside of template_ receipt.fla to see that Frame 1 is empty with
a stop action and Frame 2 (with its #P label) contains a different layout than the Invoice movie clip
inside receipt_ complete.fla.
Next, take a look at the text fields contained in Frame 2 of the Invoice movie clip inside of
template_receipt.fla and notice that all the text fields reference variable names set by
receipt_complete.fla except that all the variable names are preceded by _level0. This name
difference is due to the fact that this alternate template receipt layout is loaded dynamically from
receipt_complete into Level 1 of the Flash Player, and the dynamic text fields in this Invoice movie
clip need to peer back into Level 0 to obtain their values.
Return to the main timeline of template_receipt.fla and click on the small dot on the stage
representing the Invoice movie clip. With the ActionScript panel open, notice that this code is attached
to the movie clip:
onClipEvent (load) {
print (this, "bmax");
}
This event accomplishes two purposes. First, it waits until this movie clip has completely loaded until
performing any actions, which is great because this whole SWF file is going to be loaded into Level 1.
Secondly, once loaded, it tells Flash to print any printable frames contained within itself (by referencing
with this). In this case, the only frame marked for printing is Frame 2.
Use the File → Publish option to create an SWF file named template_receipt.swf from the
template_receipt.fla file. This SWF file should be in the same directory as
receipt_complete.fla. Then return to receipt_complete.fla and test the movie in Flash or in
your browser. Enter any values you’d like in the fields and click the Create Invoice button to view what
the printout looks like when you use the default Invoice movie clip contained inside this movie. Hold on
to this printout to do an A-B comparison with the template you’re about to implement.
Return to the Flash authoring environment for receipt_complete.fla to add the code to use the
template layout contained in template_receipt.swf to display any printed data. Click the Create
Invoice button at the bottom of the stage and change its ActionScript code to the following:
on (release) {
total=Number(mowingServices)+Number(otherServices)+Number(rawMaterials);
message="Thank You very much "+clientName+"! Have a nice day!";
loadMovieNum ("template_receipt.swf", 1);
}
The first lines of code remain the same as what was already there (these just create some new
variables), but the last line, instead of containing a print statement, now contains a loadMovieNum
action that loads template_receipt.swf into Level 1.
page 205
Server-Side Flash: Scripts, Databases, and Dynamic Development
Now you can test the receipt_complete.fla movie in Flash or your browser, enter some values in
the text fields, and view the new print layout. No additional steps are necessary because as soon as the
template_receipt.swf file arrives in Level 1, its Invoice movie clip and clipEvent execute the
action to print itself out, with its text field variables referencing values from _level0, which is the main
timeline of receipt_complete.swf.
Use the page you printed out previously to do a comparison between the two layouts. Figure 6-9
presents a visual representation of the differences between the two printed layouts (without any values
filled in).
You’ve successfully loaded a completely different receipt layout! This capability enables you to create all
kinds of dynamic files that you can load in to be printed out that can reference data pulled in from
somewhere else in the Flash Player. Alternatively, they might not contain any text fields and might just
be great-looking graphics that you want the user to be able to print.
Figure 6-9: The differences between the default receipt/invoice layout contained within
receipt_comlete.fla and the external one loaded in from template_receipt.fla.
There’s one stone left unturned here, though. You may be thinking to yourself, “Why even bother
loading into _level1 when you can load the template_receipt. swf file into the target
_root.invoice in _level0, thereby replacing the default invoice with the new one?" Good question.
The answer is because it doesn’t work! When you load an SWF file into a target, any dynamic text fields
you’re trying to print can’t properly pull their values from where they need to in time to send them to the
printer. All graphic images display properly, however, so feel free to load external SWF files into targets
(instead of levels) if all you need to do is print their great-looking graphics.
Tip Using the onClipEvent(load) action is a great way to create a quick and easy
preloader for any movie clip, including the ones in this last example. It saves you
the trouble of having to manually create a preloader if you have only one (or a few)
movie clips that need to exist in the SWF file you’re loading into Flash.
Summary
Flash’s printing feature is an amazing way to add dynamic interactivity to your Flash movie. Imagine a
viewers’ surprise when they click a button and images come out of their printers that are nowhere to be
seen in the Flash movie! Most people are used to printing out Web pages where what they see is what
they get. Flash adds the element of surprise, especially when a very large document can come out of a
very tiny Flash movie. Use Flash’s printing feature when it’s appropriate and Web viewers will delight in
returning to your site because you’ve created a complete interactive experience that bridges the gap
between the online and offline worlds.
A chart, a radio button, and a table are examples of objects you can make with a Generator template to
enhance the looks of your Web site. Generator objects can be understood in two wholly different but
related contexts. One context is a static one where data files provide one-time information for an object
to be placed in a Flash movie and then on a Web page. Another context for Generator objects is one
where data in the Generator templates is changed dynamically so that new data can be sent to the
template and the object’s appearance and even sound can be changed. For example, a user may want
information about his or her stock portfolio, and with online processing of the Generator template, the
latest data can be entered into the template, and a unique and updated chart can be presented on the
Web page.
What the two contexts have in common is that the data sources and format are similar. Once the format
is established, all that needs to be changed in a dynamic context is the data. This chapter examines the
process of formatting data for different Generator objects and the tools used to create objects and data
formats for storing data used in different objects.
Figure 7-1: The Generator Object palette provides the common set of objects associated with Generator.
page 207
Server-Side Flash: Scripts, Databases, and Dynamic Development
To access the Generator Object palette, choose Window → Generator Objects. If you’re working with
Generator objects, Flash doesn’t require you to open the palette anew each time you work on a movie.
Like other palettes and panels, the Generator Object palette will be be on the screen if left there when
you close Flash.
Open the Generator panel by choosing Window → Panels → Generator. Depending on which object
you have selected when you begin using the Generator panel, you will see different displays. Some
displays of the panel have several options and parameters while others have relatively few. For
example, Figure 7-2 shows the Generator panel that appears when the Basic Charts object is selected.
Figure 7-2: The Generator panel that appears when the Basic Charts object is selected shows a wide range
of options.
Most of the work done with Generator involves the use of the Generator Object palette and panel. In
addition, you will be using a text editor such as Windows WordPad or Macinosh SimpleText. Generator
uses data from the text files to fill the templates you develop when you are using the Generator panel.
page 208
Server-Side Flash: Scripts, Databases, and Dynamic Development
Name-and-value format
The name-and-value format is set up to read variable names and their associated single value from a
text file. The left column is for the variable name, and the right column is for the variable’s associated
value. In the first row, the labels name and value are both required in the following format:
name, value
Below the column labels, place the variable name, a comma (,), and the variable’s value. Quotation
marks are optional except where a comma is part of the value. For example, the following shows a
legitimate list of variables and their values:
name, value
primate, monkey
whale, "Oh wow, look at that!"
population, 5776
growth, "280,543,321"
China, 1,345,324,198
Variable Output
Primate monkey
Whale Oh wow, look at that!
Population 5776
Growth 280,543,321
China 1
The only surprise is China. Because no quotes were placed around China’s value, only the number to
the left of the second comma in the line appears.
Defining variables in this manner is much different than using the standard URL encoding with
ampersands discussed in Chapter 1. Because Generator likes its variables in this format, you cannot
just load name/value pairs from a URL-encoded text file without first rearranging the data to conform to
the new format outlined here. In fact, you’ll notice the complete absence of any URL encoding in
dynamic text files containing Generator variable data.
The next step after defining Generator name/value pairs is to use those variables and values inside a
Generator template. Normally in ActionScript you would just reference the variable’s name in your code,
and Flash would insert the value. When creating a Generator template, however, you need to place the
variable’s name inside of curly braces ({}) to reference it either directly in a text field or in a parameter of
the Generator panel.
Throughout this chapter you’ll be using the Generator panel to enter parameter values for each
Generator object. If you want to reference a variable in an external text file (formatted for Generator)
instead of directly specifying that value in Flash, you can just put the variable’s name in curly braces.
For example, in the previous table the Population variable has a value of 5776. If you wanted
Generator to pull this variable from the external text file and use its value as a Generator parameter, you
would type {Population} into the appropriate parameter field of the Generator panel.
As you’ve seen throughout the book, another great place to put variable values in your Flash movies is
dynamic text fields. Normally when not using a Generator template, you need dynamic text fields to get
the values of any variables displayed on the stage. When using a Generator template with external text
file variables formatted for Generator, however, you don’t need a dynamic text field! All you have to do
is place static text on the stage, and anywhere you want Flash to insert the value of a variable, just
place the variable’s name in curly braces. For example, if you had an external Generator data text file
that defines a variable named coolProgram to have a value of Flash, you could put the following
static text on the stage:
I really love {coolProgram} !!!
Whenever Flash processed the Generator template, the viewer of the final Flash movie would see these
words on the stage:
page 209
Server-Side Flash: Scripts, Databases, and Dynamic Development
This process is known as creating a placeholder for your variables, and later in this chapter, you’ll be
using placeholders like these to dynamically place externally loaded text on the stage, all without any
dynamic text fields!
Use this second format when you have several variables and more than one value for each variable. If
you are attempting to compare seasonal sales in four regions, for example, the seasons could be the
variables, and the regions could be the different values that the variables contain. Stacked bar, line, and
area charts are objects that require more than a single value for a variable. The following shows an
example of how data might be organized to show how a company’s products sold during the first half of
the year and the second:
Hardware, Software, Services
250, 340, 440
833, "2,232", "3,121"
The optional quotation marks work the same way they do in the name-and-value format. Generally, it’s
a good habit to place quotation marks around all of the values, and the quotation marks are absolutely
necessary when the value contains a comma you want to preserve. As you will see in the following
section, all objects require data in one of these two formats.
The Basic Charts object is actually several different charts in a single object template. We are starting
with a simple bar chart, and then we will look at the other types of charts associated with this object.
The minimum data requirement is a single value column, but you can optionally include a color column,
and we have done so in the example. Use the following steps to set up a basic bar chart and data
source:
1. Drag the Basic Charts icon from the Generator Objects palette to the stage. Select
the object, and using the Info panel, change the dimensions to W=400, H=300. Save
the file as Chart1.fla. Figure 7-3 shows what your movie should look like at this
point. Note the Info panel values.
page 210
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-3: Once an object is on the stage, you can resize it using the Info panel.
2. Open a text editor such as Notepad (Windows) or SimpleText (Macintosh) and enter
the following code, including the headings:
3. value, color
4. 9,#079933
5. 21,#A6F3C0
6. 30,#A6A640
7. 43,#803333
8. 12,#FFFF80
9. 29,#999999
Save the file as chart1.txt in the same folder as the Flash file you just saved.
10. Open the Generator panel by choosing Window → Panels → Generator. (You can
close the Generator Object palette because you won’t need it to complete this movie.)
Use the following list as a guide to the settings you will choose. Some of the
selections, such as Chart Type, Labels, and Max Y-Pos Type, have pop-up menus.
When you click the chart parameter, the pop-up menu appears. When you click Color,
a color well appears, and double-clicking the color well causes a color picker to
appear.
Basic Charts
Data Source: chart1.txt
Chart Type: Bar
Symbol: leave blank
Max Data Entries: default
Gap: 75
Depth: 100
Labels: on
Label Format: Arial
Horizontal Label Orientation: vertical
Horizontal Label Scale: half
Value Format: Arial
Value Placement: On Bar
page 211
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-4: The settings listed in step 3 produced this 3-D bar chart.
Stacked charts
Data Source is the most important setting in the Generator panel. If you change the Chart Type setting
from a bar chart to either a line or an area chart, you can use the same data source, but the other charts
available in the Basic Charts object require different data sets. For example, the following data shows
four variables named after a company’s regional markets and a color variable. Each of the variables has
two values that can be shown on a stacked chart that could be used to compare business in the first
and second half of a year. The top row of values appears in the top portion of the chart and the bottom
row in the bottom portion of the chart bars. Note also that the chart uses a text file in the column name-
and-value format rather than the name-and-value format of the unstacked charts.
North, East, South, West, Color
10,15,20,8,#FF260C
page 212
Server-Side Flash: Scripts, Databases, and Dynamic Development
20,11,14,22,#B3B399
Save this data in a file named chart2.txt. Leave all of the parameters in the Generator panel the same
except change the Data Source setting to chart2.txt and the Chart Type setting to Stacked Bar. Figure
7-5 shows the resulting chart.
Figure 7-5: Stacked charts require different sets of data and formats than unstacked bar, line, or area
charts.
Change the Chart Type setting from Stacked Bar to Stacked Line and Stacked Area and test the results.
You can change some of the parameters to experiment with a design that works with the rest of the
movie and the site you’re preparing the chart for.
Scatter charts
The final basic chart is the scatter chart. Generator provides both scatter and line scatter versions.
Scatter charts focus attention on key events and can show trends in specific directions based on several
data points. Minimally, the chart requires an X and a Y column. Type the following data into your text
editor and save the text file as chart3.txt.
X,Y
14,30
45,50
70, 40
90, 60
115,90
Scatter charts require some different parameter settings and optimally could use a symbol as well. This
next set of steps shows how to set up a scatter chart:
1.Use the Oval tool to draw a circle with a green radial fill with the dimensions W=13,
H=13. Select the circle and press the F8 key to open the Symbol Properties dialog
box, and then select Graphic for Behavior. Type in greenPlot for the symbol’s
name in the Name box. Click OK.
page 213
Server-Side Flash: Scripts, Databases, and Dynamic Development
2.If the little ball you just turned into a symbol is still on the stage, delete it from the
stage. Generator scatter charts will access the object in the library.
3.In the Generator panel, make the following changes:
Scatter
Data Source: chart3.txt
Chart Type: Scatter Line
Symbol: greenPlot
Value Placement: Over Bar
Grid Lines: off
Color: #FF0000
Figure 7-6 shows how the final scatter line chart appears in the SWF file.
Figure 7-6: Scatter charts focus on the data points, but the line provides trend information as well.
Lists
Generator provides four different types of list objects. Using data from external data sources, the lists
generate movie clips selected from the Clip column of the data source along with optional columns for
inserted text. Each of the three list types is examined separately.
Standard list
The List object places selected movie clips on the screen along with optional text derived from a data
source. Using Generator, you can change the movie clips or other placeholders (such as text) in the list
to update their information. For example, a Web design company may want to list its services, but it also
wants to be able to change the services or movie clips for those services regularly to keep its site
interesting and up-to-date.
This next project uses two different movie clips to generate a list of three services, using one of the
movie clips twice and the other one once. Open a new Flash page and create these three layers for the
movie:
List
page 214
Server-Side Flash: Scripts, Databases, and Dynamic Development
Labels
Title
Save the movie as List1.fla. Figure 7-7 shows the initial stage and layout.
Begin by creating a text file and saving as list1.txt in the same folder where you saved the Flash movie.
Use the following text:
Clip, service
flashMe, Engaging Flash
designMe, Cool Designs
flashMe, Backends
The first column provides the symbol names of the movie clips. The flashMe movie clip is used twice.
The second column is reserved for words that describe the service. In the movie clip, those text blocks
showing {service} will have their text replaced by the words in the second column.
Figure 7-7: The movie clips that make up the list are not placed on the stage, but they are stored in the
Library window.
List layer
On this layer, you will place the List object and set the Generator parameters. You will also create the
movie clips that the List object will pull up in the SWF file. Use the following steps:
1. Open a new Flash page and drag the List object to the stage. Select the List icon
on the page and, using the Info panel, change the dimensions to W=300, H=200.
Use Figure 7-7 as a guide for placement.
2. Open the Library window by pressing Ctrl+L or Cmd+L. Near the top of the
Library window, press the Options arrow to open the Library Options menu and
select New Symbol. When the Symbol Properties dialog box opens, select Movie
Clip for Behavior and name the movie clip designMe. Click OK.
3. In the Symbol Editing mode, add a layer and name the top layer Rock and the
bottom layer Service. Click Frame 24 in the top layer and drag the mouse down
to the bottom layer and press the F5 key to insert frames out to row 24.
page 215
Server-Side Flash: Scripts, Databases, and Dynamic Development
4. Click the first frame of the Rock layer, and in the middle of the screen, type in a
32-point bold letter D using the Trajan font or another serif font you like. Use the
Info panel to center the letter in position X=0, Y=0 relative to the center of the
stage.
5. Click Frame 12 and press the F6 key to insert a keyframe. Select the letter, and
in the Transform panel, click the Rotate button and type in 45 for the degree
angle.
6. Click Frame 24 and press F6 to insert a keyframe. Change the rotation of the
letter to 0 using the Transform panel. Figure 7-8 shows the movie clip in the
Symbol Editing mode.
Figure 7-8: The movie clips provide both the animation and placeholders for the variable
text used in the list.
7. Click Frame 1 in the Service layer and type in {service} in 14-point Verdana font
as shown in Figure 7-8. Use the Info panel to set the text block to W=200. Note
that the variable text can be much longer than the placeholder variable name
(“service” is one of the two columns in the list1.txt text file). Choose Edit → Edit
Movie from the menu bar to exit the Symbol Editing mode.
8. Repeat steps 2 through 7 and create a second movie clip. Use any animation
you want, but keep the scale small enough to serve as an icon in a list, roughly
55 by 55 in dimension. Name the movie clip flashMe, and check to make sure
that it exists in the Library window. Also be sure to include a {service}
placeholder next to the main icon.
9. Fill in the Generator panel cells as shown in the following list:
List
Data Source: list1.txt
Orientation: vertical
Mask to box: false
Spacing: auto
Item space: 30
Horizontal Alignment: left
Vertical Alignment: top
Instance name: leave blank
page 216
Server-Side Flash: Scripts, Databases, and Dynamic Development
Labels layer
Before starting this layer, drop in a dark blue background color (#003399) by choosing Modify → Movie
and then selecting the color from the background color well. This layer is where you can place your
labels for the list. In this movie, we just put in the title A*C*M*E W*E*B, the name of a little-known and
fictitious (as far as we could tell) Web design outfit serving the uninhabited deserts around Gila Bend,
Arizona. You can add any other appropriate labels required. Use the Text tool with a 24-point bold
Verdana and a cream color (#FFFFCC) to create the label.
Title layer
The Title layer is a backdrop for the List object. You may have noticed that when you put in the
background color that the List object placeholder remained white. To provide a background color for the
List object, you need a colored image behind it. Use the Rectangle tool to place a rectangle with the
dimensions W=350, H=250 behind the List object. Position the layer so that it approximates the screen
shown in Figure 7-7. Test the movie and you should see something like Figure 7-9 in your SWF file.
Figure 7-9: The data source provides specific text for the text variables and the order and type of symbols in
the list.
Scrolling list
A scrolling list is almost like the standard list except that you can scroll it up and down. The scrolling is
accomplished by adding two buttons: one to scroll up and one to scroll down. Also, you must use the
Scrolling List object instead of the List object. By making a few changes in the standard list movie from
the last section, you can create a scrolling movie.
A scrolling list works by a play() action being issued to the Scrolling List object using the instance name
of the object. The Scrolling List object is treated as and addressed as a movie clip and the play() action
initiates the scrolling movement. To reverse the movement, a script must issue a prevFrame() action
addressed to the instance name of the Scrolling List object. That’s really all there is to it. Using the
List1.fla movie, this next set of steps shows how to make changes to the movie to transform it into a
scrolling list:
1.Open the List1.fla movie and save it under the name ScrollMe.fla. Add a
layer and name it Buttons. Select the List object and delete it. In its place, drag a
page 217
Server-Side Flash: Scripts, Databases, and Dynamic Development
Scrolling List object from the Generator Object palette to the stage and resize it to
the dimensions W=300, H=200.
2.In a text editor, write and save the following text as list2.txt:
3. Clip, service
4. flashMe, Engaging Flash
5. designMe, Cool Designs
6. flashMe, Backends
7. designMe, Navigation
8. flashMe, E-business Solutions
designMe, Low Bandwidth
9.Open the Generator panel and put in the following values. One important difference
to note is that the Mask to box parameter is true. By making it true, you prevent the
objects from appearing out of the scrolling list box and in the title. Also, you must
have an instance name. In this case, roll is used to reference the Scrolling List
object. The step size determines the scrolling speed. Higher values increase the
scroll speed, and lower values decrease it.
Scrolling List
Data Source: List2.txt
Orientation: vertical
Mask to box: true
Step size: 10
Spacing: auto
Item space: 25
Horizontal Alignment: left
Vertical Alignment: top
Instance name: roll
10. Click the Button layer and create two arrow buttons, one pointing upward and one
downward. For the up arrow, use the following script:
11. on (release) {
12. _root.roll.play();
}
13. Enter the down arrow script to move the movie one frame down for each click:
14. on (release) {
15. _root.roll.prevFrame();
}
Figure 7-10 shows how the revised list movie now appears.
page 218
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-10: By adding scroll buttons and the accompanying ActionScript, a list can be as long as you need
it.
Ticker
A Ticker object works like an automatic scrolling list. Using the same data source as the ScrollMe.fla,
you can quickly center the Flash movie around a Ticker object instead of a scrolling list. The following
steps show how:
1.Save the ScrollMe.fla movie as TickerIt.fla. Delete both buttons and the
Scroll List object on the stage. Drag a Ticker object from the bottom of the
Generator Object palette to the stage. Adjust the Ticker object size to W=300,
W=200.
2.Select the Ticker object and fill out the Generator panel as shown in the following list:
Ticker
Data Source: List2.txt
Orientation: vertical
Mask to box: true
Step size: 4
Spacing: auto
Item space: 0
Horizontal Alignment: left
Vertical Alignment: top
Instance name: leave blank
That’s all there is to it. You don’t need an instance name for ActionScript to target because the Ticker
object is self-starting and scrolls automatically and continuously.
page 219
Server-Side Flash: Scripts, Databases, and Dynamic Development
Multipage list
The final list object is one that depends heavily on symbols and the data source. The Multipage List
object is typically the only object on the stage, and a single layer and frame make up the movie. All the
work is done in filling out the Generator panel, creating symbols, and arranging the data source. The
key to this object is planning.
Our example of a multipage list is a project management one. For tracking purposes, a project is broken
down into a number of tasks, and each task in the project is assigned to one or more individuals. As the
project grows and changes, the individuals involved and the tasks they assume change, and for very
large projects, a multipage list helps keep track of everyone. To add a bit of e-world project
management to the list, we assumed that none of the people are in contact except by e-mail. As tasks
and individuals are added or removed from the project, their names and duties can be changed in the
data source text file. Figure 7-11 shows the initial page of the SWF file with a multipage object.
Figure 7-11: The initial page contains a heading from a text symbol and a customized navigation pointer.
page 220
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 221
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-12: The Multipage object automatically arranges the navigation symbols on the page and will
navigate to the next, previous or home (first) page in the movie.
Pie chart
Pie charts are used for displaying distribution. If a company is attempting to keep track of expenses, for
example, one way to quickly see what organizational units are costing the most is to place all of the unit
expenses into a pie chart. In Generator, all of the pie charts show proportional representation based on
a given set of values. So although absolute values are displayed on each pie slice, what you are
actually seeing is a slice based on the value’s proportion to the whole. As a result, you can see both
absolute and proportional values simultaneously.
To create a pie chart, you need a two-column data source. One column contains the values to be
placed in the slices, and the other column is a color code. In your text editor, type in the following table
and save it as myPie.txt.
Value,Color
56,#EE452B
44,#DECC00
26,#6E5E00
28,#C5660C
54,#FFE673
33,#FFB340
Caution Avoid using black as a color code if your labels are going to be placed on top
of the slices because the text color is black.
After you have your data source, look at this next set of steps to find out how to create a pie chart. As
you will see, it is one of the easiest charts to create.
1. Open a new Flash page and drag a Pie Chart object icon onto the stage. Using the
Info panel, set the dimensions of the icon to W=400, H=400.
page 222
Server-Side Flash: Scripts, Databases, and Dynamic Development
2. Select the Pie Chart icon, open the Generator panel, and then enter the following
values:
Pie Chart
Data Source: myPie.txt
Depth: 350
Value Display: Always
Value Format: Arial
Value Placement: Inside
Value Scale: Half
External Symbol File: leave blank
Border: False
Border Thickness: leave blank
Color: leave blank
Instance name: leave blank
The values can be placed inside or outside of the slices. If a slice is too small to contain a value, the
value is automatically placed on the outside of the slice. If you select Half on the Value Scale, the
values are more likely to be small enough to fit within the slices, and they tend not to overwhelm. Figure
7-13 shows the SWF file with the parameters and data used in this example.
Figure 7-13: Pie charts are used to show distribution quickly and clearly.
Plot
The Plot object relies heavily on movie clips and the data source because the Generator panel itself
requires little data other than minimum and maximum parameters. Movie clips can be simple or
complex, and depending on how you use the Plot object, you can give it an instance name to be
referenced and used with ActionScript.
The basic use of a Plot object, however, is to create a way of displaying data points using one or more
movie clips. In this respect, it is not unlike a Scatter object. The main difference lies in the control you
have over the clips in the plot. In addition to controlling the x- and y-coordinates, you can control the
size (scale) and rotation of the objects.
page 223
Server-Side Flash: Scripts, Databases, and Dynamic Development
Suppose you have a client with products in both domestic and international markets. You want to show
how well different products are doing in both markets, how profitable the product is, and what the
performance is relative to the previous year. In addition, you have new products that you want the same
information about, except for the comparison to the previous year. The plot’s vertical axis represents
sales in international markets, and the horizontal axis represents the domestic market. The size (scale)
of the movie clip represents the product’s profitability. Established products are represented by triangles
that point upward for a better performance than the previous year, downward for poorer performance,
and sideways for no change. New products are represented by green circles; the scale of each circle
reflects that product’s profitability (bigger is more profitable). With this type of information, the plot
shows at a glance the three different types of information for each product and, in the plot context, how
each product is faring relative to the others.
To set up this project, open a new Flash page and use the following layers:
Plot
Label
Save the movie as ThickPlot.fla and then start putting the parts together.
Plot layer
Select the Plot layer in the movie and follow these steps to get started:
1.Drag a Plot object from the Generator Object palette to the stage. Select the Plot
object and, using the Info panel, set the dimensions to W=400, H=350.
2.The Plot object allows you the option to substitute names for the different columns
instead of using the default names such as X and Y or Xscale and Yscale. This
example takes advantage of that feature and renames the x-axis Domestic and
the y-axis International. Using such names helps remind you what each is used
for when entering the data in the data source. In the Generator panel, enter the
following values:
Plot
Data Source: myPlot.txt
Min X-Pos: 0
Max X-Pos: 100
Min Y-Pos: 0
Max Y-Pos: 100
X Column: Domestic
Y Column: International
X-Scale Column: leave blank
Y-Scale Column: leave blank
Rotate Column: leave blank
Symbol Name Column: leave blank
Instance Column: leave blank
Border: on
Border Color: black
Border Thickness: 20
Instance name: leave blank
3.Open up a text editor and enter the following text and save it as myPlot.txt. Notice
that instead of using X and Y columns for the x/y position of the data points, we are
able to substitute Domestic and International.
4. Clip,Domestic,International,Xscale,Yscale,Rotate
5. NewProd,50,70,0.5,0.5,0
6. NewProd,20,50,1,1,0
7. NewProd,70,20,1.5,1.5,0
8. NewProd,60,80,0.2,0.2,0
9. Prod, 7,10,0.7,0.7,180
10. Prod, 45,20,0.2,0.2,90
11. Prod, 70,70,1.5,1.5,0
12. Prod, 23,67,0.5,0.5,180
Prod, 92,40,0.3,0.3,0
page 224
Server-Side Flash: Scripts, Databases, and Dynamic Development
Label layer
In this layer, you need to add labels to the horizontal and vertical axis. This layer would also be a good
place to create the movie clips needed to represent the product categories. The following steps outline
the process:
1.Use a dark green (#006600), 14-point, bold Verdana font to type the word
International along the left side of the Plot object icon. After each letter, press
Enter/Return to create a vertical label in all caps. With the same font type in all
capital letters, type the word Domestic directly beneath the Plot object icon on the
stage. After each letter, press the space bar to add some breathing room for the
label because it’s in all capital letters.
2.Press Ctrl+F8 or Cmd+F8 to open Symbol Properties dialog box. Select Movie Clip
for Behavior and enter Prod for the name. Click OK to enter the Symbol Editing
mode. Draw a triangle with a yellow (#FFCC00) fill and black stroke with
dimensions of H=40, W=40.
3.Repeat step 2 using the name NewProd and drawing a circle with a dark green
(#006600) fill with the same dimensions of H=40, W=40 as the other symbol.
After you have completed the movie, test it. Figure 7-14 shows the SWF file you should see. Change
the parameters in the data source file to experiment with placement and scale.
Figure 7-14: The Plot object enables you to dynamically place symbols and control their placement, scale,
and rotation properties.
Stock chart
The Stock Chart object is optimized for tracking stocks, but you can use it for other data that have a
beginning value, an ending value, and highs and lows in between. Weather values, for example, could
be usefully plotted on such a chart. Like the Plot object, the Stock Chart object relies on the information
placed into the Generator panel and data source.
The data source for the Stock Chart object requires four column headings: Open, Close, High, and Low.
Each value can be expressed as either an integer or a floating-point number. But you cannot put in
page 225
Server-Side Flash: Scripts, Databases, and Dynamic Development
fractions, such as 10 3⁄8. All fractions must be expressed as decimals. For example, type the following
text in a text editor and save it as StockPortfolio.txt in the same folder as your Flash movie.
Open, Close, High, Low
22,25,27.3,21.2
25,27.5,28.3,24.7
27.5,27.8,29.9,26.2
27,25,28.3,22
25,30,31.3,23.7
30,22,33.3,21.2
22,25,27.3,21.2
Open a new Flash page and save it as StockExchange.fla. Rename the layer Stock and most of your
work is done. The only other task is to drag a Stock Chart icon from the Generator Object palette, resize
it to the dimensions H=400, Y=350, and then enter the following data in the Generator panel. When
you’re finished, save your file. Figure 7-15 shows the finished Flash movie.
Stock Chart
Start Offset: 0
Gap: 0
Labels: On
Grid Lines: on
Major Gridlines: 5
page 226
Server-Side Flash: Scripts, Databases, and Dynamic Development
Minor Gridlines: 2
Max Y-Pos :0
Max Y-Pos: 50
Border: true
Border Thickness: 20
Line Thickness: 20
Color: #B38026
Figure 7-15: Vertical lines in the Candlestick format show the highs and lows; the boxes show the opening
and closing values.
Table
The Table object is a bit trickier than it would appear to be. Each element in the table is a symbol,
including all the text. The text symbols provide placeholders for the different text material in the table.
The data source contains the same number of symbols as the number of cells in the table. Each column
positions the material in the corresponding column in the table. To best understand how tables work in
Generator, begin with the following text, which constitutes a data source used in the sample table. Enter
the data in a text editor and save it as QuickTable.txt. (Note how the data has been grouped in rows of
three; that grouping is for purposes of clarification only.)
Clip,phone,address
page 227
Server-Side Flash: Scripts, Databases, and Dynamic Development
Ambulance,0,0
phone,911,0
address,0,521 E. Arlington
Police,0,0
phone,911,0
address,0,211 Orange Road
Fire,0,0
phone,911,0
address,0,832 Polk Street
Bus, 0,0
phone,555-6843,0
address,0,99 Main Street
Information,0,0
phone,555-INFO,0
address,0,6772 Apricot Lane
The first column on top refers to the movie clips used as row headings, and each of the two other
column headings are for variables named in the text symbols. The groupings of three rows represent
the three columns in each row. For example, the third grouping of data after the column headings
begins with Fire. In this project, we used a fire engine symbol to begin the row and followed it with the
phone number. In the second row of the grouping, the clip is a text symbol called phone, and because
the data for the telephone number goes in the second column, the second column contains the number
911. In the next row, the address clip is used, and the data goes in the third column. Placing a 0 in the
second row ensures that the address will not be placed there incorrectly (the address goes in the third
column). By using the same name for the variable and the symbol, you can use the intersection of the
row and column of the same name to help put data in the correct place. Figure 7-16 shows the Flash
movie being prepared with several symbols containing either text or icons for row headings.
The sample movie, Table.fla, uses two layers:
Table
Labels
The table is set up to use icons to quickly identify essential services. The emergency icons have
animated flashing lights and the non-emergency icons are graphic symbols with no animation.
page 228
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-16: Symbols containing placeholders for text are an essential part of Flash movies that use
Generator Table objects.
Table layer
To set up the Table layer, drag a copy of the Table object icon from the Generator Object palette to the
stage. Resize the Table icon to the dimensions W=400, H=300. The table in the movie has five rows
and three columns. Because the cells tend to get in the way of the information in the table, the border
has been turned off. The following data shows how to fill out the Generator panel for the Table object:
Table
Rows: 5
Columns: 3
Sizing: fixed
page 229
Server-Side Flash: Scripts, Databases, and Dynamic Development
Symbol File:
Border: off
Border Color:
Border Thickness:
Instance name:
Labels layer
In the Labels layer, the focus is on setting up column labels for the table. You will have to use some
trial-and-error to position the labels just where you want them depending on precisely where the
columns appear in your table. Because no border or grid is used to separate the data, the labels must
be aligned above the correct column. Wait until you have tested your movie with all of the parts working
before trying to align the labels. For the time being, use Figures 7-16 and 7-17 as rough guides for
where to type in the Essential Services title and Service, Phone, and Address headings. You can
make adjustments later.
The heart of Table objects lies in preparing the text symbols and row symbols. Use the following steps
as a guide:
1.Prepare the text symbol by choosing Insert → New Symbol from the menu bar to
open the Symbol Properties dialog box. Enter phone as the name, Graphic as the
Behavior, and then click OK. You are now in the Symbol Editing mode.
2.Select the Text tool and use a 14-point purple type to type {phone}. That creates the
phone variable placeholder. Select the text box, and in the Info panel, set the width
to W=140. Remember that the text box has to be long enough to hold data that
may be longer than the variable name.
3.Repeat steps 1 and 2 to create a second text symbol and use the variable name
{address}. Set the width of the text box to W=180.
4.Repeat step 1, except select Movie Clip as the Behavior. In Symbol Editing mode,
draw an ambulance and optionally add blinking lights.
5.Repeat step 4 until you have additional movie clips showing a police car, fire truck,
bus, and information symbol. You should have five movie clips total. Figure 7-17
shows you what your table will look like when it is completed.
page 230
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-17: If any of the information in a table has to be updated or changed, all you need to do is
to change the data source information.
After going through all that work to create a table in Generator, you may conclude that you could do the
same thing with less effort using HTML and a Web development tool such as Dreamweaver or GoLive.
But if your table data is regularly updated, all you need to change in a Generator table is the data itself
and the information can then be sent to all the sites that use the same data source. You don’t have to
resave a Web page or go into a site to make a new page for data that changed in one of more of the
site’s pages. Weather tables are especially well suited for the Generator Table object because their data
is updated regularly.
Replicate
Those banner ads that appear when you open a Web page in many commercial sites can be anything
from informative and effective to annoying. But if you do them right, you can get a lot of information to a
lot of people and not be a pest. Using the Replicate object from Generator, you can take any number of
symbols and put on a slide show on the Web. What’s more, once the banner is in place, you can
change it simply by changing the information in the data source.
Setting up an effective Flash movie using the Replicate object requires setting two different Generator
panels. Neither panel requires much information, but because more than a single panel must be set,
one panel must reference the data source set up in the other. The banner ad in this example is for the
fictitious company Acme HiRisk a boiler-room outfit attempting to recruit e-mail solicitors using the
Internet and home computers. Four movie clips are repeated in the banner along with text broken down
into a key remark, a question, and an answer. Begin by typing in the following data source file and
page 231
Server-Side Flash: Scripts, Databases, and Dynamic Development
saving it as rep.txt. (Added spacing between the lines is for clarity. Each of the five rows has four
columns separated by a comma and no carriage returns except at the end of each row block.)
Clip,Key,Question,Answer
page 232
Server-Side Flash: Scripts, Databases, and Dynamic Development
All that is left to do is to create four graphic symbols with the images you want to put into the banner.
Figure 7-18 shows one image and text message you will see on the stage when the movie runs.
Figure 7-18: Using the Replicate and Insert Symbol objects together, you can create animated banners that
can be easily updated by changing the information in an external data file.
For the most part, though, all you need is a simple text file. You can store that text file in any Web
server and access it by typing in the URL in the Data Source row of the Generator panel. You could, for
example, create a data file on a Windows PC, store it on a Linux-based server, and then develop the
page on a Macintosh. When the file is launched, everything will work fine.
You can specify links to external data sources containing variables and name/value pairs for the main
timeline as well as individual movie clips. Press the Generator Environment Variable button at the
upper-right corner of the timeline when you’re on the main timeline or in the editing mode of a movie clip
timeline. A small window pops up asking you to type in the path (relative or absolute) to the text file or
server script that is going to send variables back in a Generator-friendly format. There are also buttons
to specify whether the data is being delivered in column name-and-value format or name-and-value
format for simple variable declarations. Once Generator variables are loaded into the specified timeline,
any object in that timeline can use them by just referencing a variable’s name and enclosing it in curly
braces.
Note You can’t specify an external data source for the timelines of buttons or graphic
page 233
Server-Side Flash: Scripts, Databases, and Dynamic Development
symbols. You can still press the Generator Environment Variable button and
display the pop-up window, but specifying any external data sources in these
symbol types has no effect and does not load your data correctly.
One additional feature of the Data Source pop-up window is that you can directly enter your data
name/value pairs as you would if they were in an external text file. You just need to place a pound sign
(#) as the first character in the first line. So if you wanted to set three Generator name/value variables
that reside permanently in the SWT template, you would just pop open the Generator Environment Data
Source window and enter code something like the following:
#NAME, VALUE
bobAge, 26
steveAge, 32
mikeAge, 19
This method works effectively for name/value pairs only. It’s useful for setting variables that you need to
update only once in a while. You don’t want these variables ever hanging around on the server in a text
file where someone might take a look at them; they’re more secure inside of the SWT template where
no one can see them but you.
Generator demystified
Any Flash content dynamically manufactured by Generator consists of four parts that need to come
together before the final output is achieved:
The Generator SWT template created in Flash
The data source, whether internal to the SWT template or loaded from an external text
file
Any raw materials, such as images or sounds, that need to be pulled into Generator
The Generator Server program that compiles the template, data source(s), and any raw
materials into a final SWF Flash movie file
The last part concerning Generator Server can confuse you if you don’t understand what Generator
Server consists of and what it is meant to do. Generator Server is not a program in the same way that
Flash is. You can’t open it up on your desktop and use some handy drop-down menus to configure it
and perform tasks such as saving files.
Generator Server is a plug-in system for many of the most popular server types. Once installed,
Generator lurks around in the background of the server waiting for someone surfing the Web to stumble
upon a Web page containing an SWT template. When this happens, Generator springs to life and looks
at the SWT template along with data source and raw materials (if applicable) and compiles a full Flash
SWF movie that is delivered to the viewer. The person looking at the final compiled extravaganza never
knows that Generator was used at all.
Generator processing happens in the background on the server, and viewers see the final Flash movie
as they would see any other nongenerated Flash movie that may have been on the server. Using the
Generator Server in this manner is referred to as using Online Generator or Online mode because the
processing happens online and in real time each and every time a viewer looks at a Web page with an
SWT template.
You can use the Generator Server in another equally powerful and even more interesting way. This
other method is referred to as using Offline Generator or Offline mode, and it means that the Generator
Server program is not acting in real-time response to requests for Web content but is being told directly
and specifically by you (or by a CGI script you create) to manufacture Flash movies. The power in this
method lies in the fact that you can create SWT templates that have prescripted object movements
(such as moving a bitmap image around the stage) and then dynamically create a whole army of SWF
page 234
Server-Side Flash: Scripts, Databases, and Dynamic Development
Flash movies in a matter of seconds that all use identical object movements but have unique and
different objects in each SWF file!
Note Offline mode can generate more than just SWF files. It can create GIFs, JPEGs,
PNGs, Quicktime movies, text files, image maps, and both PC and Mac Projector
files. Many output file formats can be batched and generated using Offline mode,
and although you may be hard-pressed to find a use for some of them, at least
you know they exist!
The Enterprise Edition was designed for business applications, and when used in Online mode, it is
capable of processing hundreds of requests per second. Its true power lies in the fact that it can
generate real-time content for tens of thousands of Web viewers every day in Online mode. The more
processors on the server CPU, the more powerful Enterprise Edition becomes. Unfortunately, the more
generating you need it to do, the more it’s going cost you. This program can be a hard sell to cost-
conscious clients, and it’s definitely not going find its way into any mom- and-pop Web sites.
Macromedia seems to have almost priced itself out of a market where many more companies would be
using Generator and consequently thousands of more developers would take an interest in learning and
deploying Generator. Generator’s price reduction from $30,000 range is definitely helping this situation
to improve.
Enterprise Edition can be used in Offline mode as well and makes short work of whipping up massive
batches of Flash movies. It can also employ a unique feature in Online mode called caching where it
keeps track of the content most often generated; this feature enables Enterprise Edition to work even
faster. Speed is the key selling point of the Enterprise Edition, but most common folk would wait a few
extra seconds if they could save about $2,000, so Macromedia has created another edition of
Generator.
Generator Developer Edition can do everything that Enterprise Edition can do, except for the caching,
and sells for the more reasonable price of about $999. If you’re running a high-power Web site with
massive amounts of traffic and plan on using Generator in the real-time Online mode, this edition might
be too slow for your needs. In many cases, though, you’d be surprised at how admirably Developer
Edition performs in comparison to the more robust Enterprise Edition.
In Offline mode, Developer Edition performs the same exact tasks as Enterprise Edition but is
somewhat slower in manufacturing Flash files. Offline mode usually means that the content doesn’t
need to be available on a split-second basis, so a few extra seconds to process the templates doesn’t
make a difference to most people when they can save thousands of dollars. Developer Edition is
targeted more at Web developers and small Web sites, as well as people running small servers on
collocated boxes or on a DSL line out of their apartments.
Generator installation
Installing any Generator edition on your computer or Web server is fairly easy because Generator
comes with a standard installer utility. Generator can be run on Windows 95/98/2000 with or without a
Web server as well as Windows NT, Sun Solaris, or Red Hat Linux. The Offline mode will run fine on
any of these systems, although for Online mode you’ll need to be running a Web server on your
operating system so that means you need Personal Web Server 4.0 for Windows 95/98/2000, IIS for
Windows NT, Apache or Netscape for Sun, and Apache for Red Hat Linux. The newest edition of
Generator was released in March 2001 and includes support for many other Web servers operating on
these platforms. Generator doesn’t currently run on any Macintosh platform. For complete details of the
system requirements and platforms Generator supports as well as patches and updates, you can visit
www.macromedia.com.
Both Generator Enterprise Edition and Developer Edition are available for 30-day free trial download
from Macromedia’s Web site. (A trial version of the Developer Edition is also available on the CD in the
page 235
Server-Side Flash: Scripts, Databases, and Dynamic Development
back of this book.) In order to work through the examples in the upcoming section, we recommend that
you go to the Macromedia Web site and get the correct free trial version for the platform you’re using.
Don’t worry about running a Web server; we’ll be talking more about offline generating.
Once you download the trial version, make sure to uncheck the installation option for the Jrun server
extensions or any other server package listed if you don’t have a Web server running on your machine.
Also be sure to fill out your correct e-mail address on the big long form that you submit before you
download the trial version to make sure that you’ll receive the serial numbers Macromedia will
automatically send to you. You can’t install any of the Generator software without these serial numbers.
When the download is complete, just launch the file that you downloaded, and the automatic installation
will start. Choose the correct option regarding running a Web server and then enter the serial number
Macromedia e-mailed you.
Caution On most Windows machines, Generator installs to the directory C:\Program
Files\Macromedia\Generator, and we recommend that you let it install to this
directory because this path is the one most commonly used and referenced
when Generator is targeted for the offline generating of files.
The first thing you’ll notice if you open up the directory where Generator was installed is a program
called generate.exe. You would think that clicking this program would make Generator spring to life
and perform some miraculous feats, but clicking this file displays a little MS-DOS window that just as
quickly disappears, leaving you none the wiser as to how Generator works or what it does. Generator
has no GUI (Graphical User Interface) whatsoever; you have to launch and configure it using the
archaic commands of the MS-DOS command line.
Note The trial versions of Generator automatically stick the Macromedia logo into all
SWF files. It always appears at a different location on the stage, and it always
reminds you that you’re dealing with a trial version of Generator. With this logo
floating around all the time, you’ll find it difficult to use the Generator trial version
for anything but learning Generator and deciding whether it’s the right solution for
you.
Online Generator
Online Generator is a very simple way to generate Flash content. If you have one of the supported Web
server programs installed on your computer, you can start generating online content immediately.
Anytime the server receives a request for an SWT file, Generator springs to life and dynamically
delivers the compiled SWF file to the Web browser that requested it. Try placing some SWT templates
in your server directories along with any associated data source files and accessing them via a Web
browser. You should see the generated SWF files if you installed Generator correctly.
Note The many ins and outs of using and troubleshooting Online Generator are beyond
the scope of this book. Because each server type has so many of its own
subtleties, a good portion of the money you pay when buying one of the
Generator editions is earmarked for tech-support. If you have problems, check
Macromedia’s Web site for tech notes or give Macromedia a call.
One of the options you have in Online mode is passing variables to the SWT template via a query string
much like the methods described at the end of Chapter 1 for doing this with Flash files. The SWT file is
embedded in the <object> and <embed> tags of the HTML page exactly where the Flash SWF file
would normally go. All the same options and parameters apply, you just have to specify an SWT file
instead of an SWF file. You can pass a query string of URL-encoded variables into the SWT file by just
amending it to a query string in either the HTML code or the ASP/PHP/CGI code if you’re generating
your HTML pages dynamically. For example, the code to place an SWT template named
worldmap.swt on an HTML page and pass it a variable named countryName with a value of United
States would read as follows:
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash
/swflash.cab#version=5,0,0,0" WIDTH=400 HEIGHT=300>
<PARAM NAME=movie VALUE="worldmap.swt?countryName=United%20States">
<PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#FFFFFF>
<EMBED src=" worldmap.swt?countryName=United%20States "
quality=high bgcolor=#FFFFFF WIDTH=400 HEIGHT=300
TYPE="application/x-shockwave-flash"
page 236
Server-Side Flash: Scripts, Databases, and Dynamic Development
PLUGINSPAGE="http://www.macromedia.com/shockwave/download
/index.cgi?P1_Prod_Version=ShockwaveFlash"></EMBED>
</OBJECT>
Many people reading this book probably don’t have a Web server at their immediate disposal where
they can install something like Generator. Most hosting companies will not let you install software such
as Generator unless you own or collocate your server at that company. Very few companies offer
Generator hosting, but they do appear from time to time. But keep in mind that the pricing structure of
Generator is such that it is to be sold to the end client and not to be bought and resold by a hosting
company.
Offline Generator
You can use Generator in Offline mode if you’re running one of the supported operating systems and
regardless of whether you have any Web server software installed. The most common application is on
Windows 95/98/2000 and Windows NT, so the paths and parameters in this section relate directly to
those installations.
Offline Generator allows you to take the SWT templates you create in Flash and use them to output
many different file types, including SWF Flash movies. In the following example, you’ll create a
Generator SWT template with a JPEG image object that performs a motion tween. You’ll then use
Offline Generator to insert five different JPEG images into the template and create five different SWF
files in a matter of seconds. The commands and parameters are sent to Generator via a batch (BAT) file
written in a simple text editor and executed by Windows.
page 237
Server-Side Flash: Scripts, Databases, and Dynamic Development
To create a simple batch file that jumps to the directory containing Generator, follow these steps:
1.Open a new text file in your favorite Windows text editor.
2.Enter the following code into the first line of the text file:
cd C:\PROGRA~1\MACROM~1\GENERA~1
3.Save the file as testing123.bat on your desktop.
4.Go to your desktop and double-click on the testing123.bat file.
You should see an MS-DOS output window appear showing the path to the Generator directory similar
to what you saw in the MS-DOS command line example. The difference here is that you can’t type in
the window that just popped up; it’s for output only, and it shows you that the commands in your batch
file were properly executed. If they weren’t executed properly, the window will display the error
messages.
In the example in the next section, you’ll be creating a similar batch file to make Generator do your
bidding. All you’ll need to do is add a few simple commands and parameters following the first cd line of
code, and you’ll be creating lots of generated files in no time.
Note If you installed Generator into a directory other than C:\Program Files\
Macromedia\Generator, you’ll have to compensate for this by placing the
correct path to your Generator installation in the cd line of the batch file.
page 238
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 239
Server-Side Flash: Scripts, Databases, and Dynamic Development
The next important parameter to understand is -param. This parameter lets you directly send values for
Generator variables into the SWT template and appears in the batch file at the very end of the
generate code line following the SWT template declaration. The -param parameter is followed by the
variable name you’d like to define, a space, and then the variable’s value:
cd C:\PROGRA~1\MACROM~1\GENERA~1
generate -swf C:\MyWebFiles\spaceship.swf
C:\gendocs\shiptemp.swt -param totalHoops 75
This code would set a Generator variable named totalHoops with a value of 75 on the main timeline
of the shiptemp.swt template. Note that there is no carriage return or line break in the code, even
though it appears as two lines here because of formatting constraints. In your text editor, the generate
code line should be continuous. You can also set more than one variable, although you’ll need a
separate -param designation for each:
cd C:\PROGRA~1\MACROM~1\GENERA~1
generate -swf C:\MyWebFiles\spaceship.swf
C:\gendocs\shiptemp.swt -param totalHoops 75
-param totalPenguins 42
This code would send an additional Generator variable named totalPenguins with a value of 42 to
the main timeline of shiptemp.swt. Keep in mind that these are Generator variables and not ActionScript
variables. To make use of the variables you’re piping into the SWT template, you’ll have to be
referencing them somewhere with curly braces (for example, {totalPenguins}) somewhere in a
Generator template object parameter or a text field on the stage.
page 240
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-20: The layout of the stage and timeline for pictemplate.fla.
page 241
Server-Side Flash: Scripts, Databases, and Dynamic Development
12. Create a new file your favorite text editor (preferably Notepad) and save it as
makemovies.bat inside your C:\gendocs folder. Add the following code lines to
the file and then save your changes:
13. cd C:\PROGRA~1\MACROM~1\GENERA~1
14. generate -swf C:\gendocs\myMovie1.swf
15. C:\gendocs\pictemplate.swt -param imageName flashcore1.jpg
16. generate -swf C:\gendocs\myMovie2.swf
17. C:\gendocs\pictemplate.swt -param imageName flashcore2.jpg
18. generate -swf C:\gendocs\myMovie3.swf
19. C:\gendocs\pictemplate.swt -param imageName flashcore3.jpg
20. generate -swf C:\gendocs\myMovie4.swf
21. C:\gendocs\pictemplate.swt -param imageName flashcore4.jpg
22. generate -swf C:\gendocs\myMovie5.swf
C:\gendocs\pictemplate.swt -param imageName flashcore5.jpg
Please note that although the text as viewed here has several lines, the only carriage retruns
that should be present are after the very first line and then after every JPG file declaration.
This makemovies.bat file is available on the CD-ROM for reference.
23. Navigate to C:\gendocs folder using Windows and then double-click your
makemovies.bat file to put Generator to work creating five unique Flash movies
that each use one of the JPEG images you put in the folder.
The MS-DOS output window should spring to life and show that Generator is creating each file. After it’s
done, you should have five new files in your C:\gendocs directory sequentially named
myMovie1.swf through myMovie5.swf. Double-click any one of these files to launch them and see
how Generator plugged each unique JPEG image into the template and performed the scaling and
motion tweening. You’ll also notice that Generator plugs in the value for the imageName variable in the
lower-left corner of the stage. If you’re using the trial version of Generator, you’ll also get the great
Macromedia logo randomly strewn about all the movies. Figure 7-21 shows the approximate output for
one of the movies.
page 242
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 7-21: Generator has used the SWT template and one of the JPEG images to create an entire Flash
movie.
Let’s take a closer look at the code in the batch file to go over some of the finer points of the generation
process. The first line contains the change directory cd command to tell Windows where to look for the
Generator program installed on your hard drive. The rest of the lines use the generate command and
are all identical except for their sequential numbering of JPEG images and output files. We used -swf
to tell Generator to make a Flash movie and then place it in the C:\gendocs directory with a name of
myMovie1.swf. Immediately following that is the path to and name of the template for Generator to
use which is C:\gendocs\ pictemplate.swt . Finally, the imageName variable that the SWT
template needs to find the right JPEG image and also fill in the text field on the stage is defined in the
batch file. Notice that the only thing separating the variable name imageName from its value
flashcore1.jpg is a simple space:
generate -swf C:\gendocs\myMovie1.swf C:\gendocs\pictemplate.swt -param imageName
flashcore1.jpg
Notice that in each generate code line the numbers following myMovie1 and flashcore1 are
incremented by one to tell Generator to use a different JPEG image and then create a new and unique
SWF file.
Tip As long you’re connected to the Internet while running Generator, you can specify
an http:// reference for an image name in either the SWT template, Generator data
text file, or -param section of a batch file. For instance, in the previous example,
you could easily replace flashcore1.jpg with something like http://
www.mydomain.com/anyimage.jpg.
You can use Offline Generator to create many different types of files. In the previous sample project, try
changing the -swf reference in the batch file to -xwin32 instead. This reference will create Flash
Projector files to run in Windows. Just remember to also change the swf file extensions to exe after
each myMovie reference in the batch file as well.
page 243
Server-Side Flash: Scripts, Databases, and Dynamic Development
The one possible drawback to creating lots and lots of files with a Generator batch file is the large
amount of code you’d have to enter in the BAT file. You can save time by having any scripting
language, including ActionScript, create your batch files for you. As a side project, try creating a simple
admin system in Flash that takes input data from a variety of text fields and and then outputting all the
lines of properly formatted batch code into a single dynamic text field by using some if/then/for
loops. You can just cut and paste from the Flash text field into a new batch file in Notepad, save it, and
then run it from Windows to have Generator create 50 or 100 different files.
pageOutput = Executor.ExecuteDosApp
Response.Write "<pre>" & pageOutput & "</pre>"
Using ASP in this manner is very powerful because you could easily specify filenames, templates, or
Generator variables via ASP and even include information from a database in your instructions to
Generator. ASPExec can also listen for responses from MS-DOS, and you can have ASP wait until
Generator is finished to proceed to some other task.
Cross- For more information about using ASP with Flash, be sure to read
Reference Chapter 3.
Alternatives to Generator
Using Generator has its drawbacks. One is the obvious expense of buying the software license for your
particular application, but there are a few other drawbacks you need to be aware of as well. Generator
is a dynamic tool and, therefore, when you are using it in Online mode, there can sometimes be a delay
on the server while Generator creates the SWF file.
Imagine if the page the SWT template sits on as well as the data source for that template are generated
by ASP. That would be three times that the server has to be called upon to create content: one time for
the initial page, a second time to have Generator come to life and process the SWT template, and a
third when that template calls for a data source dynamically generated by another ASP file. Finally, the
server has to deliver the final Flash movie to the viewer’s Web browser. Although servers are usually
pretty fast, a process as intricate as this one can induce some lag. Every Web server and CPU is
different though, so you always want to test your Web project under a variety of possible conditions to
see if there is a possibility of a slowdown anywhere and make appropriate adjustments to your content
or strategy.
A few small development companies have built products to compete with Generator that do basically
the same types of things on the server side. You still use the same objects in Flash to build your SWT
templates, but you then use these other ‘generators’ to serve up the content in an online or offline
capacity. One of the most popular is Swift Generator, which you can find online for a fairly low price. In
fact, it’s completely free for noncommercial use. Other developers have built products in Perl and even
PHP in some cases. These products are good to play around with, but if you need to generate dynamic
page 244
Server-Side Flash: Scripts, Databases, and Dynamic Development
content in a mission-critical environment, it’s best to stick with Macromedia Generator and take
advantage of the great tech support that accompanies the purchase of the full version of Generator.
Summary
Macromedia Generator is a unique and powerful tool with an even more unique price tag. It definitely
has uses for large Web projects that need constantly updated dynamic Flash content. Once a Generator
system is built for a client, that client can create new Flash movies by doing nothing more than changing
some simple files in a Web directory. Even when complex Generator data files are needed, they can be
created via ASP, PHP, and/or Perl with an admin system to make data entry easy. Offline Generator
can be a big time-saver as well for repeatedly creating massive amounts of Flash movies, even for a
small Web site.
The Generator 2 Developer Edition might be a great investment for even a small to midsize project to
save time and energy, especially if many of the artists and developers working on the project have a
limited knowledge of Flash and/or Generator. Finally, with a really cool GUI interface featuring lots of
pre-scripted features and a slimmer price tag, it’s our belief that Generator could be a dominating force
in Web development, with a much wider user base than exists today. Even in it’s current state it’s
definitely worth downloading the trial version and checking it out with the examples in this chapter!
Although this chapter is titled “Dynamic Game Development,” it presents some valuable concepts that
can enhance just about any Flash movie. As soon as you create a Flash movie where the user can
manipulate objects or where your objects act according to certain rules and boundaries, you are in
essence creating a game, even if that is not your intention. Many companies choose Flash so that they
can express their message in an entertaining and engaging atmosphere.
You may already be familiar with some concepts in this chapter; others will be new for you. All of the
concepts deal with object manipulation and the most efficient ways to track multiple objects. (Although
basic principles of movement will be covered, the concepts behind creating 3-D engines and emulating
the gravity of the planet Jupiter are best left for a book on physics.) This chapter will change the way
you think about building interactive Flash movies, especially ones using object tracking and collision
detection.
A new ActionScript command has unbelievable interactive power; it can change the way you build
interactive Flash movies by enabling you to find movie clips and operate on them without having ever
given them an instance name. Rather than save it for the end, we present this command first, because it
is the foundation on which we’ll be building many of the later examples.
page 245
Server-Side Flash: Scripts, Databases, and Dynamic Development
Wouldn’t it be nice if Flash could just take a look at the stage and figure out what was there all by itself?
For example, it could know that ten aliens are on the screen and test whether the lasers firing from the
spaceship are hitting each alien, and when a new alien appears, it could test the lasers against that one,
too.
Suppose you had a shoebox with a few marbles in it. If someone asked you to roll all the marbles down
to one end of the shoebox, you wouldn’t have to explain that you don’t know their instance names. You
would just look in the box, see how many marbles there were, and roll them all down to the end of the
shoebox. If someone added a marble to the box and asked you to now roll all the marbles to the other
side, you wouldn’t have to say that you can’t because the new marble hadn’t been added to an array
tracking the existence of all current marbles. You would just look inside the shoebox again and move
them all to other side, the new one included.
You’re capable of performing these actions because you can see with your eyes what’s going on in that
shoebox. Flash can see now, too, in very much the same way with the new and largely undocumented
For/In statement.
To see this statement in action, let’s create a simple Flash movie that illustrates the box of marbles
example mentioned previously.
1. Create a new Flash file and save it to your hard drive as marbles.fla.
2. Use the Oval tool with a stroke color of black and fill color of red to create a circle on
the stage. Use the Scale tool and the Info panel to make the circle a size of about 35
by 35. Place this red circle somewhere in the upper left-hand corner of the stage.
3. Select the entire red circle and press F8 to turn it into a movie clip with the symbol
name of Button.
4. Use the Oval tool with a stroke color of black and fill color of blue to create a circle on
the stage. Use the scale tool and the Info panel to make the circle a size of about 20
by 20. This circle is the marble.
5. Select the entire blue circle and press F8 to turn it into a movie clip with the symbol
name of Marble.
6. Do not give the blue circle an instance name on the stage. Instead, select it and
duplicate it five times to give you a total of six marbles on the stage, all without
instance names.
7. Place the marbles somewhat close together at the center of the top of the stage.
Using the Rectangle tool with a black stroke and no fill color, draw a vertical rectangle
around the marbles (to represent the shoebox) with these dimensions: W=140,
H=320.
8. Select this rectangular outline along with all the marbles and press F8 to turn them all
into a movie clip with a symbol name of Shoebox. You should now have a main
timeline stage containing a red button along with a movie clip of the shoebox that has
six Marble movie clips nested inside it. Figure 8-1 depicts what this stage should look
like.
page 246
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 8-1: The layout of the stage containing the Shoebox movie clip with six nested Marble
movie clips inside it.
9. Give the Shoebox movie clip an instance name of shoebox. The shoebox needs an
instance name so that you can tell Flash where to look for the marbles.
10. Select the red button and attach this ActionScript to it:
11. on(press){
12. for(eachMarble in _root.shoebox){
13. _root.shoebox[eachMarble]._y+=10;
14. }
}
Test the movie in Flash or your browser and click the red button. Each time you click it you should see
all the blue Marble movie clips inside the Shoebox movie clip moving down to the opposite end of the
stage. If you don’t, make sure you completed all of the preceding steps or open the marbles.fla file
on the CD-ROM for reference.
What’s happening in this movie is quite interesting. Flash takes a look inside the shoebox and sees six
Marble movie clips. It then increases each one’s y-coordinate by 10 pixels. The amazing thing is that
you never name any of the marble instances! You don’t have to track their names in an array or figure
out how many there are. Try editing the Shoebox movie clip and placing more Marble movie clips inside
or deleting some. The result is always the same. Flash knows how many movie clips are inside the
Shoebox movie clip through the power of the For/In ActionScript statement.
Note Before we dissect the For/In statement, you must realize that when you didn’t
name those Marble movie clip instances, Flash named them for you. Every movie
clip on every timeline must be assigned a name. Usually you will name the movie
clip with the Instance panel, but if you don’t, Flash names them for you with
names such as Instance1 or Instance35 where the digit at the end of the name is
incremented for each movie clip Flash finds on each timeline. This naming
system made little difference before Flash 5 because you couldn’t target the
page 247
Server-Side Flash: Scripts, Databases, and Dynamic Development
instance names without knowing what they were. Now with the For/In action you
can!
page 248
Server-Side Flash: Scripts, Databases, and Dynamic Development
eval("_root.shoebox."+eachMarble)._y+=10;
Regardless of whether you choose to use the bracket method of evaluation or the eval action, you
must always remember to include the path again inside the For/In statement. Later in this chapter and
the next, we’ll explain some shortcuts to ease your typing chores if you have extremely long paths to the
objects you’re targeting with the For/In statement. Looking at the correct initial syntax once again:
for(eachMarble in _root.shoebox){
_root.shoebox[eachMarble]._y+=10;
}
it performs the duty of targeting each movie clip inside of shoebox and then increasing its y-coordinate
by 10 pixels. When Flash finds the last object inside of _root.shoebox, it stops executing the For/In
statement.
Try giving each marble an instance name. Pick any names you’d like. Test the movie again and notice
that names appear in a seemingly random order in the output text field. This order is actually their
stacking order on the timeline of the Shoebox movie clip. Go back to the marbles, and with one marble
selected, choose Modify → Arrange → Send To Back. You’ll notice upon testing the movie again that
the name of the movie clip you sent to the bottom of the stacking order appears last in the dynamic text
field. Movie clips at the top of the stacking order are the ones Flash finds first.
page 249
Server-Side Flash: Scripts, Databases, and Dynamic Development
Try adding some other kinds of objects into the same file:
1. Select the Shoebox movie clip on the main timeline. Add the following ActionScript to
it:
2. onClipEvent(load){
3. someWord="FlashCore";
4. someDigits=12345;
5. prettyColors=new Array("red","green","blue");
6. function doNothing(){
7. //Just for fun
8. }
9. emptyContainer=new Object;
}
10. Preview the movie again and click the red button to see that Flash has found all the
objects you defined, as well as the movie clips.
11. To have Flash figure out the types of all the objects inside the Shoebox movie clip,
change the red button code to the following:
12. on(press){
13. output="";
14. for(eachObj in _root.shoebox){
15. output+=eachObj+"-"+typeof(_root.shoebox[eachObj])+newline;
16. }
}
17. Save the new file you’ve created as object_types.fla; you’ll use it later. (It’s also
available on the CD-ROM if you have any difficulties.)
When you test the movie and click the red button, Flash not only shows the name of each object it found
in the shoebox, but the type of that object as well. This result is accomplished via the typeof
ActionScript, which returns a string specifying that the object in question is either a movieclip,
function, object, or in the case of a variable, a number or a string. Figure 8-2 shows an example
of this output.
page 250
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 8-2: Flash has found many movie clips as well as other objects inside the Shoebox movie clip and
has returned their correct type.
What does this have to do with shooting aliens with laser guns? Quite a bit actually, and we’ll get to all
that in a moment. First you have to make a clean, reusable version of the For/In code that you can
plug into any dynamic Flash movie.
page 251
Server-Side Flash: Scripts, Databases, and Dynamic Development
or
if(typeof(finalObj) eq "movieclip"){
finalObj._visible=0;
}
The last statement would take any movie clips that Flash found inside the specified masterObj object
and set their _visible property to 0, making them invisible.
Note You can also specify a timeline as the path by using _root, this, or a level number.
This kind of specification can get messy, though, because Flash can start to look
at the very movie clips or objects that are executing the For/In statement.
Therefore, we recommend choosing a path that is different from the path that the
For/In statement is being executed from. In this case, it’s being executed from a
button on the _root, so you wouldn’t want to specify a masterObj of _root or you
might find some confusing things happening. Additional if statements that filter
unwanted objects with typeof can often solve this problem though.
page 252
Server-Side Flash: Scripts, Databases, and Dynamic Development
if(_root.laser.hitTest(_root.spaceship.alien)){
score+=100;
_root.spaceship.alien.gotoAndPlay("vaporized");
}
if(_root.key.hitTest(_root.lock)){
_root.door.gotoAndStop("open");
}
You can see that the basic premise behind hitTest is usually to check whether two movie clips
happen to be touching and then if they are touching, to perform an action on one of the objects. You
can make anything happen as the result of hitTest though, as in the third if statement that utilizes a
key and a lock.
page 253
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
Using the onclipEvent(enterFrame) ActionScript means that Flash will execute these
statements over and over at the current frame rate of the movie.
17. Test the movie in Flash or in your browser and click the blue circle to start dragging it
around. As soon as it touches the red circle, the red circle will disappear as is about
to happen in Figure 8-3. The completed file is available on the CD-ROM as
basic_collision.fla if you experience any difficulties.
Figure 8-3: When the blue circle being dragged touches the red circle, the red circle will
disappear.
The ActionScript behind this movie is fairly straightforward. Using the onClipEvent(enterFrame)
statement attached to itself, the Draggable MC movie clip that contains the blue button repeatedly
checks to see whether it has touched _root.redCircle. If the touching occurs, the ActionScript sets
the visibility of _root.redCircle to 0 and makes it disappear.
Note The self-reference object this is used in this example because the ActionScript
testing for the collision is on one of the objects being tested. You can easily
replace this with _root.blueCircle in the code and test for the collision from
anywhere in the entire Flash movie. Many times, though, using this is easier
because you’ll be putting hit testing onto duplicated movie clips whose names
may be difficult to keep track of.
This example shows hitTest at its most basic level, with only two movie clips and one clip doing the
hit testing. Try adding the following code to the Red Circle movie clip:
onClipEvent(enterFrame){
if(this.hitTest(_root.blueCircle)){
_root.blueCircle._visible=0;
}
}
Now you have both clips testing to see whether they’ve hit each other. When you test the movie, you’ll
see that they both disappear! The ActionScript on each clip affects the other one.
page 254
Server-Side Flash: Scripts, Databases, and Dynamic Development
Try different actions with the movie clips. Instead of making the circles invisible, set the _alpha to a
different setting or change the height and width of the circles. You can add multiple statements inside
the hitTest action, so you could have code that keeps score or tells another movie clip to stop or play.
Experiment by putting all kinds of actions inside the bounds of the hitTest action.
page 255
Server-Side Flash: Scripts, Databases, and Dynamic Development
duplicated clip.
Note that blue circle is being hit tested against itself, which evaluates to true because the blue circle is
indeed “touching itself” all the time. It then tries to remove itself but it can’t, because it’s a master
instance and not a duplicate clip. To see this occurrence in action, change the
finalObj.removeMovieClip(); line in the onClipEvent of the blue circle to
finalObj._alpha=50;
Upon testing the movie, you’ll see the blue circle immediately change its alpha to 50 percent. As you
drag the blue circle over each red circle, it turns to 50 percent alpha as well. What’s happening is that
the blue circle hit tests true to itself as soon as the movie starts and changes its own alpha. This
occurrence is important to keep in mind when using For/In; generally you should check for objects
nested in a completely different timeline if you’re going to use For/In for collision detection. When you
were previously using the removeMovieClip code you didn’t notice any effect on the blue circle
because it was an original clip and couldn’t be removed. Now that you’re changing _alpha, the code is
effecting every object in the designated path including the blue circle. Figure 8-4 illustrates the changing
of the alpha for the hit-tested movie clips.
Figure 8-4: As the blue circles contact the red circles, their alpha is changed to 50 percent.
Here it’s okay because the original goal was to remove the duplicate clips. The original red circle is
made invisible as soon as all the duplicates are done in the frame action
_root.redCircle._visible=0; because otherwise the circle would never be removed, because it,
like the blue circle, also is a master instance and not a duplicate clip. Instead of making it invisible, you
could also place it off to the side of the stage where it would never be seen in the final exported file.
We’re getting closer to building a real game. For example, imagine that instead of dragging that blue
circle around, you were operating it with your keyboard arrow keys. Or suppose that blue circle
represents just one of many small objects that represent laser blasts from a canon, and each time one
of these laser blasts hits its target, the target disappears! Feel free as you work through the examples to
substitute any of your own graphics for the simple shapes presented here.
page 256
Server-Side Flash: Scripts, Databases, and Dynamic Development
This example expands on the file you created in the last example where you can drag the blue circle
around to make the duplicated red circles disappear. You’ll make some changes to add keyboard
control to the blue circle and also give it a cannonball weapon to destroy the evil red circles!
On the CD- Use the file you created from the last example or open the
ROM collision_for_in.fla file on the CD-ROM.
1. On the main timeline, delete all the frame actions from Frame 1. You’ll no longer be
duplicating the red circles from here.
2. Select the red circle on the main timeline; it should have an instance name of
redCircle. Press F8 to wrap another movie clip around it. Name this new movie clip
symbol Multiple Circles and give it an instance name on the main timeline of
multipleCircles.
3. Double-click the multipleCircles movie clip instance on the main timeline to get into its
editing mode. The redCircle instance should be the only thing inside it. On Frame 1 of
the Multiple Circles timeline, add this frame action:
4. for(i=1; i<=10; i++){
5. redCircle.duplicateMovieClip("redCircle"+i,i);
6. this["redCircle"+i]._x=Math.random()*500;
7. this["redCircle"+i]._y=Math.random()*200;
8. }
redCircle._visible=0;
This action duplicates the red circles on the Multiple Circles timeline, and all the duplicates
become objects nested inside the Multiple Circles timeline. The path to access one of them
would be something like _root.multipleCircles.redCircle7.
9. Return to the main timeline and test the movie. You should see the circles duplicated,
but they are probably off in one corner because Flash is randomly placing them in
relationship to the center of the multipleCircles movie clip and not the main timeline.
To correct for this problem, place the multipleCircles instance on the main timeline at
an x-coordinate and y-coordinate of 0 by using the Info panel. When you test the
movie again, the duplicated red circles appear randomly across the top of the stage.
10. To make a cannonball to be fired at the red circles, choose Insert → New Symbol and
choose movie clip. Then enter Cannonball for the name of the movie clip. You
should now be inside the Cannonball movie clip with a blank stage in front of you.
11. Using the Oval tool with a stroke color of black and a fill color of green, place a circle
on the stage where the x- and y-coordinates are equal to 0. Use the Info panel to
change the circle’s dimensions to 15 by 15. Select this entire circle and press F8 to
turn it into a graphic named Ball.
12. Within the Cannonball movie clip, select Frame 10 on the timeline and press F6 to
create another keyframe. In this Frame 10 keyframe, adjust the coordinates of the
green ball graphic you created to be X:0 and Y: -100. These coordinates should place
the green ball higher than the center of the clip by 100 pixels.
13. Select any frame between Frame 1 and Frame 10 and create a motion tween with
Insert → Motion Tween.
14. Select Frame 11 now and press F7 to place a blank keyframe in this frame. Add the
frame action: stop(); to this keyframe. The timeline of the Cannonball movie clip is
now complete. Figure 8-5 shows the layout of the Cannonball movie clip.
page 257
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 8-5: The layout of the timeline inside the Cannonball movie clip.
15. Press Enter on your keyboard to observe the cannonball flying forward 70 pixels
ready to eradicate the enemy.
16. Return to the main timeline and drag an instance of the completed Cannonball movie
clip to the stage. Position the movie clip somewhere off to the left of the main portion
of the stage, with a negative x-coordinate in the Info panel. This setting hides the
initial cannonball from the viewers. Select the movie clip and give it an instance name
of ball.
17. Position the blue circle anywhere in the lower half of the stage. Save this file to your
hard drive as cannonball.fla. Figure 8-6 shows the stage layout at this point.
page 258
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 8-6: The layout of the timeline inside the cannonball.fla file.
page 259
Server-Side Flash: Scripts, Databases, and Dynamic Development
changed by the amount specified in the dist variable, which is set to 5 here. You can change this
amount to suit your need for speed; increasing the distance increases the speed of the blue circle’s
movements.
The ActionScript on this clip is using simple if statements and the key action to check whether one of
the arrow keys on your keyboard is pressed. Each key action, such as Key.isDown(Key.UP), refers to a
specific key on your keyboard, such as the up arrow key in this example. A complete listing of all the
possible key codes and combinations is included in the ActionScript reference that comes with Flash.
You now need to add one more key action to fire a cannonball (seemingly) from the blue circle toward
the enemy red circles when you press the spacebar. Select the blueCircle movie clip instance and
double-click it to edit its master symbol instance Draggable MC. Inside this clip is the Drag Button button
that has the drag actions on it. Add the following extra on action to this button:
on (keyPress "<Space>") {
count+=1;
_root.ball.duplicateMovieClip("ball"+count,count);
_root["ball"+count]._x=this._x;
_root["ball"+count]._y=this._y;
}
Test the movie and use your arrow keys to move the blue circle around. Press the spacebar at any time
to launch a cannonball. No hit testing is occurring yet, so all the red circles stay put, but you see the
effect. This effect is the result of attaching a keyPress action to the button inside the blue circle. Each
time you press the spacebar, a new Cannonball movie clip is generated on the main timeline and is
positioned on the current stage location of the blue circle. The last two lines of code reference the
circle’s _x and _y properties to pinpoint the correct position.
This code places the Cannonball movie clip in the exact center of the blue circle. But if you wanted the
Cannonball clip more at the blue circle’s “vertical top,” you could change the last line of code to the
following:
_root["ball"+count]._y=(this._y-(this._height/2));
This line of code would place the cannonball duplicates at the vertical top of the blue circle clip by
figuring out the circle’s height property and adjusting the _y position for the cannonball accordingly.
We didn’t have to attach this section of code to the button inside the blue circle. It could easily have
been placed on any button anywhere in the movie. The only difference would be that you’d need to
specify blueCircle as the clip for the cannonball to "snap to" by naming it specifically:
_root["ball"+count]._x=_root.blueCircle._x;
_root["ball"+count]._y=_root.blueCircle._y;
You may also be wondering why we didn’t just attach this whole section of code to the cannonball
instance ball itself using an if (Key.isDown(Key.SPACE)) code block right after the if statements for the
arrow keys. We could do that, but because the onClipEvent(enterFrame) actions execute over and over
as fast as the movie frame rate, you would get a constant barrage of cannonballs flying out when the
spacebar is held down. If you want this effect, feel free to use the clip duplication and positioning actions
in this manner.
page 260
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
Save your file, test the movie, and fire away! You should be able to destroy all the red circles on the
stage by launching your cannonballs with the spacebar. Try using your mouse to click and drag the blue
circle around while firing as well. If you encounter any problems, the completed file is available on the
CD-ROM as cannonball.fla.
The code you added to the cannonball should be very familiar. The only piece of it that needed to be
altered from the standard template for the For/In and hitTest code was the path to _root.multipleCircles,
which is the container movie clip for all the duplicated circles.
Tip As you play, you may notice that Flash starts to slow down after more and more
cannonballs have been fired. This slowing down is because all those duplicated
cannonball movie clips are still laying around on the stage, even though they’ve
stopped at their blank keyframe in Frame 11 of the Cannonball movie clip. The way
to fix this is to select Frame 11 inside of the Cannonball movie clip, add the line of
code this.removeMoveClip(); below the stop() action, and save your file
again. You’ll now have full speed at all times, because Flash will be removing each
duplicate cannonball as soon as it reaches the end of its range.
page 261
Server-Side Flash: Scripts, Databases, and Dynamic Development
Test the movie to see that anytime the blue circle touches any of the red circles it slowly begins to fade
out. You could easily replace the line of code with _alpha to make anything happen to the blue circle
that you want.
Keeping score
To implement a scoring system, follow these steps:
1.The one layer on the timeline is getting mighty crowded, so create a layer above the
existing one and name this layer Scoreboard.
2.In the Scoreboard layer, create a dynamic text field in the upper right corner of the
stage and enter score in the Variable text box in in the Text Options panel. Make
sure that the Border/Bg check box is checked so that you can see the score better.
3.Change the onClipEvent(enterFrame) code block on the ball instance of the
Cannonball movie clip on the stage to have one extra line of code:
4. onClipEvent(enterFrame){
5. masterObj=_root.multipleCircles;
6. for(eachObj in masterObj){
7. finalObj=masterObj[eachObj];
8. if(this.hitTest(finalObj)){
9. finalObj.removeMovieClip();
10. _root.score+=100;
11. }
12. }
}
13. Test the movie and note that you can now keep score! Every time you blast one of
the red circles, your score will increase by 100.
page 262
Server-Side Flash: Scripts, Databases, and Dynamic Development
16. Test the movie again and wow! You have all kinds of circles of different sizes and
rotations moving in different directions. Figure 8-7 shows the effect on the stage of
the SWF movie. The only problem with the circles’ movements now is that the
circles all begin and end their cycles at the same time. To fix this problem, you
need to add a randomized play statement to the redCircle clip inside the Multiple
Circles movie clip.
Figure 8-7: The red circle objects in the game have been randomized in size and direction of
movement.
17. From the Library, double-click the Multiple Circles movie clip to get into its editing
mode. Select the instance of redCircle movie clip you see there and attach this clip
action to it:
18. onClipEvent(load){
19. rnd=Math.floor(Math.random()*20);
20. gotoAndPlay(rnd);
}
21. Save your movie as cannonball_enhanced.fla (it’s also on the CD-ROM). Test the
movie once again and you’ll see that you have a very random game.
The more random a game becomes the less predictable it is and the more fun it is to play. Each red
circle starts its movement cycle on a different frame thanks to the rnd variable that is used in the
gotoAndPlay statement. If the Math.floor statement is confusing, it’s just the new Flash 5 way to do what
in Flash 4 looked like
rnd=int(random(20));
which looks a lot cleaner than that Math.floor statement. Unfortunately, both the rnd action and the
random action have been deprecated in Flash 5, so we all need to start using the Math object with its
methods and properties.
Caution You may be wondering why you have to add the playhead randomizer actions
as an onClipEvent and not just stick them in the Frame 1 action of the
Multiple Circles movie clip where all the circles are duplicated and their sizes
page 263
Server-Side Flash: Scripts, Databases, and Dynamic Development
are adjusted. The problem is that in order to control the playhead in a movie
clip, you need to instantiate the movie clip, which means it must exist first.
Until Flash’s entire playback mechanism moves another frame beyond where
it duplicates the movie clip, the clip doesn’t exist yet and, therefore, any
actions specifying a timeline control like gotoAndPlay need to be put
somewhere other than the code block where you duplicate those movie clips.
This is an anomaly for sure, but it’s one you should be aware of.
page 264
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
}
}
onClipEvent(load){
_rotation=Math.random()*360;
}
Because we specified the masterObj here to be _root.multipleCircles, we’re calling the makeOneCircle()
function inside of it that as we know, creates another red circle. Test the movie and you’ll see that every
time you shoot down one of the circles another pops up to replace it.
Try moving your blue circle up to where the upper left-hand corner of the stage would be, where that
original red circle is placed in the authoring environment. You probably notice your blue circle fading
out. This occurs because even though the original red circle’s visibility has been set to false, the circle is
still there. To fix this problem, first remember that in the For/In/hitTest combinations we’ve used the
eachObj variable to represent the instance name of each movie clip Flash encounters. Because you
know that the original redCircle movie clip contains a name that is nine letters long and all the
duplicated clip names are longer because they have a digit tacked on them, you just make sure that
eachObj has more than nine letters. To do this, find the statements on both the cannonballs and the
blue circle that read
if(this.hitTest(finalObj)){
Now the hit testing will work only if the instance of the red circle that Flash finds has a name longer than
nine characters, meaning that it cannot be the original hidden red circle.
On the CD- All of the project modifications in this section and the following section are
ROM available in the file cannonball_enhanced2.fla on the CD-ROM.
Whenever the score reaches over 2000, the game will be over because the black square will obscure
everything except the cannonballs that have been duplicated to higher levels. For a quick workaround
for situations like this, keep in mind that Flash has 16,000 levels to duplicate movie clips to (0 to
15,999), and you can use the higher levels to place objects above all the other objects in a timeline,
even duplicate ones. In this example, you would change your code on your GAME OVER movie clip to
the following:
onClipEvent(load){
this._visible=false;
}
onClipEvent(enterFrame){
if(_root.score>2000){
this._visible=true;
this.duplicateMovieClip(this,15999);
page 265
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
}
If you’re getting the picture that building an involved game requires a lot of planning, you’re 110 percent
correct! Each time you need to add an element, you need to adjust for other elements. As your game
building progresses, you’ll get better at planning out all the elements.
Summary
Many of the core basics of building an interactive game are presented in this chapter. Assuming you’ve
worked with Flash for a while now, you know that there are typically 25 ways to accomplish the same
thing. ActionScript is very much a creative tool, and programmers have unique artistic styles. Just
because certain actions were placed in certain places in this chapter (on a button versus a frame versus
a clip action) doesn’t mean that you must always put them there. These actions were placed where they
work well in this chapter’s game, but you can apply the core pieces of the code examples wherever they
best fit into your game schema. Happy gaming!
Obstacles
Obstacles are objects that you want to prevent another object from passing through. Obstacles are
probably one of the most important concepts to master in gaming because without any obstacles,
objects in your game are always free to go wherever they please. It does no good to build a maze game
if your character can walk right over the walls of a maze as if they weren’t there to begin with! You can
use obstacles to build walls and traps and other places that you want to keep the objects in your game
from touching.
You can also use obstacles to confine an object to an area. For example, the old arcade game Sprint
involved racing a car around a racetrack, and the car could move only if it was on the racetrack road
surface. The second you approached the edge of the track, the game would let your car drive no further.
In this section of the chapter, you create some objects that can move around in free space and then
place obstacles in that space to make it less free.
Objects in your game need to be free to move in any direction the user chooses to be somewhat
realistic. For example, when you walk around a room, you can turn in any direction that you want and
not just increments of 45 of 90 degrees. In this project, you create a character that walks around a room
in much the same way.
On the CD- Copy the file man.fla from the CD-ROM to your hard drive and open it in
ROM Flash for editing.
The file man.fla on the CD-ROM contains an overhead view of a character created by Nate Yarrington
of entertainovision.com. The character is a movie clip of a little man that contains 11 frames of what is
known as a walk cycle. Test the movie in Flash and you see that, as the movie clip plays, the man goes
through the cycle of walking with his hands swinging at his sides and his little feet moving back and
forth. Our goal in this project is to give this little man the capability to walk forward and backward as well
as turn in any of 360 degrees. The real trick, though, is that after he’s turned facing a certain direction,
he moves in that direction instead of just increments of 45 or 90 degrees.
The first thing to do is create an object that can spin in any degree of 360 degrees and then move in the
direction it’s facing in the same way that your car moves in the direction it’s facing no matter how many
degrees you turn the wheel. After you complete the movement ActionScript, you could easily replace
the graphics in the movie clip with those of a racecar, a boat, an animal, or anything else you can dream
up. In the Flash authoring environment for man.fla, start the process by selecting the Man movie clip
on the stage and adding the clip actions in Listing 9-1.
Listing 9-1: Setting Walk and Rotation Speed
page 266
Server-Side Flash: Scripts, Databases, and Dynamic Development
onClipEvent (enterFrame) {
if (Key.isDown(Key.UP)) {
speed = 5;
this.Play();
else if (Key.isDown(Key.DOWN)) {
speed = -5;
this.Play();
else {
speed = 0;
gotoAndStop (4);
if (Key.isDown(Key.RIGHT)) {
angleChange = 10;
} else if (Key.isDown(Key.LEFT)) {
angleChange = -10;
} else {
angleChange = 0;
The statements in Listing 9-1 are nested within an onClipEvent statement, which means that they
constantly execute as long as the movie clip of the little man exists on the stage. The first set of if
statements deals with setting a walk speed. The speed is set in pixels in a variable named speed. This
movie also has a frame rate of 25 frames per second (fps), which is critical for smooth movement. A
frame rate of 12 fps does not look as good.
The if(Key.isDown) statements look to see whether a key is pressed. If the up arrow key,
(Key.UP), is pressed, the speed is set at 5 pixels. If the down arrow key, (Key.DOWN), is pressed,
the speed is set at -5 pixels to enable backward movement. Notice that following each of the speed
settings is a statement telling this movie clip to play() so that the man moves his legs and does not
just float across the screen.
The last else statement in the //Set walk speed code block tells Flash that, if neither the up arrow
or down arrow keys is pressed, the man is to stand still. (His speed is set at 0.) The gotoAndStop(4)
statement in this section of code stops the playhead in this movie clip at Frame 4. Frame 4 of the man’s
walk cycle is the one where he most looks as though he’s standing still.
page 267
Server-Side Flash: Scripts, Databases, and Dynamic Development
The set of if statements in the //Set rotation speed code block check to see whether the right-
or left-arrow key is pressed. If one of these keys is pressed, a variable named angleChange is either
set to 10 for clockwise movement or -10 for counter-clockwise movement. Basically, this code sets the
variable that denotes how fast the angle changes as you press the right- or left-arrow keys. You add the
code to actually rotate the man next.
Test the movie. The only thing that works right now is that, after you press either the up-arrow or down-
arrow key on your keyboard, the man moves through his walk cycle. If no arrow key is pressed, the man
stands perfectly still.
Now you can add the rest of the code to get this little guy moving. Still within the same onClipEvent
statement that you created with Listing 9-1, add the code in Listing 9-2 right after the closing curly brace
of the angleChange=0 statement. Save the file as man_walking.fla.
Listing 9-2: Making the Man Move
myAngle = myAngle+angleChange;
if (myAngle<0) {
myAngle += 360;
else if (myAngle>360) {
myAngle -= 360;
xchange = (xmove*-1)+(speed*Math.sin(Math.PI/180*myAngle));
ychange = (ymove*-1)-(speed*Math.cos(Math.PI/180*myAngle));
xmove +=xchange;
ymove +=ychange;
this._y+=ymove;
this._x+=xmove;
this._rotation=myAngle;
The first line of code in Listing 9-2 adds myAngle to any possible angleChange put forth by the arrow
keys. If you look at the very last line in Listing 9-2, you see that the code eventually gets around to
setting the little man’s rotation to equal myAngle. Before that happens, though, the angle is constrained
by the block of code following //Keep myAngle between 0 and 360. This code constantly checks
page 268
Server-Side Flash: Scripts, Databases, and Dynamic Development
to see whether the angle or rotation you’re setting is less than 0 or greater than 360. If either of those
occurrences is true, the myAngle variable is adjusted by +/- 360 degrees to keep you from ending up
with angles such as 1,243 degrees.
The next segment of code, beginning with //Calculate the distance to move x and y, uses
some physics and geometry and introduces the xchange, ychange, xmove, and ymove variables.
The first time through the loop, before any arrow keys are pressed, the variables’ values are 0. But as
soon as a positive or negative speed number is detected, it is combined with whatever angle is set in
myAngle to create new coordinate values that are then added to the previous coordinate values in
these statements:
xmove +=xchange;
ymove +=ychange;
Explaining all the geometry and trigonometry involved in this code is beyond the scope of this book, but
basically what is happening is that all the variables being set with the arrow keys are being evaluated
and worked into some x- and y-coordinate changes that you can use to move the little man.
In the last block of code, which begins with //Move the little man, the movie clip’s x-position and
y-position are updated to reflect changes. Because the man can move in any direction, the values for
the xmove and ymove variables can easily be negative numbers. You can take a look at all the variable
values by enabling the debugger and testing the movie. The very last line of code sets the visual
rotation of the movie clip to equal the angle set in the myAngle variable.
Test the movie in Flash or your browser. By pressing the up- or down-arrow keys, you can move the
man forward and backward. If the arrow keys aren’t having any effect, use your mouse pointer to first
click anywhere on the stage of the Flash movie. Pressing and holding the down-arrow key makes the
man do a little “Moon Walk” dance move across the stage. Pressing the right- or left-arrow key spins
him around. You also can use arrow-key combinations to get neat angular movement effects. You’re
probably beginning to see how you could adapt this code to use with a boat or racecar. If you’re
experiencing any problems with the file you just created, make sure that you recheck your steps and
reference the completed man_walking.fla file on the CD-ROM.
Note If you’re testing the movie in a browser, you may notice that none of your arrow
keys are having any effect at first. For the arrow keys to work, the Flash movie in
the Web page you’re looking at must be the focus. You achieve this focus by
clicking anywhere in the Flash movie using your mouse. If you develop games,
you should always include a Start the Game button to make sure that the user
clicked somewhere in the Flash movie and switched the focus of the Web
browser to the Flash movie so that it can then accept keyboard input.
Obstacles are a great way to place boundaries in your games or dynamic Flash movies beyond which
objects cannot pass. Creating the graphic for an obstacle is quite easy because you can make it look
any way that you want. The hard part is testing to see whether an object that is moving has hit the
obstacle and, if it has, constraining that object’s movement to prevent it from getting around the
obstacle.
The basic concept we’re using here to make the obstacle work is simple. In the last chapter, you saw
how collision detection worked. The example in this chapter also tests for a collision if an object moves.
If a collision with an obstacle is detected, the object that has moved is moved back to where it was
because it cannot be allowed to pass the obstacle. You may be asking yourself, “How is that going to
look, with objects moving back and forth all the time?” The answer is that it’s going to look just fine,
because when Flash executes ActionScript code contained in a button, frame, or movie clip, Flash
doesn’t update the screen until it’s done working through all the code.
So if you move some objects around in the middle of an ActionScript code sequence, those objects are
moved virtually in Flash’s processing memory. You can then set variables based on the positions of
those objects and test those variables to see whether they fall within certain guidelines. If the guidelines
are not met (say, for example, that an object hits an obstacle or is standing right on top of it), you can
just use some ActionScript to move it back. As long as the ActionScript moving the object back to where
it was occurs farther down in the code list than the original movement code, Flash leaves the object
alone. Alternatively, you could move the object someplace new, and Flash puts it there instead.
The key thing to remember is that, for each frame cycle, Flash computes all the ActionScript code first,
and only after it’s done does it update the screen with the final results. This is great news! Now you can
move objects in a virtual manner all across the screen, see if they’re near or touching other objects, and
page 269
Server-Side Flash: Scripts, Databases, and Dynamic Development
then put them all back where they were if you need to without the person viewing the Flash movie even
seeing that you’ve done anything!
On the CD- Copy the file man_walking.fla to your hard drive and open it in Flash for
ROM modification. You can also use the version of this file that you created in
the last example if you still have it open.
onClipEvent (enterFrame) {
if (Key.isDown(Key.UP)) {
speed = 5;
this.Play();
page 270
Server-Side Flash: Scripts, Databases, and Dynamic Development
else if (Key.isDown(Key.DOWN)) {
speed = -5;
this.Play();
else {
speed = 0;
gotoAndStop (4);
if (Key.isDown(Key.RIGHT)) {
angleChange = 10;
} else if (Key.isDown(Key.LEFT)) {
angleChange = -10;
} else {
angleChange = 0;
myAngle = myAngle+angleChange;
if (myAngle<0) {
myAngle += 360;
else if (myAngle>360) {
myAngle -= 360;
xchange = (xmove*-1)+(speed*Math.sin(Math.PI/180*myAngle));
ychange = (ymove*-1)-(speed*Math.cos(Math.PI/180*myAngle));
xmove +=xchange;
page 271
Server-Side Flash: Scripts, Databases, and Dynamic Development
ymove +=ychange;
this._y+=ymove;
this._x+=xmove;
this._rotation=myAngle;
//If the man contacts an obstacle, move him back to where he was
masterObj=_root;
for(eachObj in masterObj){
finalObj=masterObj[eachObj];
this._y-=ymove;
this._x-=xmove;
Test the movie in Flash and you see that, try as you may to move the little man through or over the
obstacle block, you simply cannot do so! No matter what side and at what angle you attack the block
from, you cannot walk over it and must go around it. If you have any trouble with the code, recheck your
steps or open the completed file available on the CD-ROM as man_walking_obstacles.fla. Figure
9-1 shows the little man trying to get around the block.
page 272
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 9-1: The little Man movie clip cannot get through the obstacle you placed for him.
There’s not much point in using the For/In statement if you’re just going to have one obstacle block.
Return to the Flash authoring environment and duplicate the obstacle block that’s on the stage as many
times as you’d like. Change the scale, height, and width for all the blocks if you’d like. If you have
graphics of your own obstacles, you can throw them in, too. Just make sure that they’re movie clips.
Because you’re using For/In, you don’t need to name anything at all. A possible layout of the stage is
shown in Figure 9-2.
page 273
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 9-2: A possible layout for the stage after creating lots of obstacles and resizing them.
Try testing the movie again with all the blocks you place all around the stage and you see that you can
confine the man to an area of the stage. Using obstacles, you can easily create a maze for the man to
walk through. You can also resize the man or change his rate of movement by adjusting the speed
variable in the code or change his rate of rotation by adjusting the angleChange variable. You can also
replace the man’s graphic with any that you’d like to use.
Caution Although obstacle collision detection is darn good, it’s not completely
foolproof. Don’t create an obstacle-driven game where the winning prize is a
million dollars or anything really valuable. You may have noticed that the little
man occasionally gets stuck on an obstacle, although 99 percent of the time
he can get free by spinning around. Some of this sticking has to do with his
shadow and his arms. Changing his rate of movement can also affect the
obstacle “bounce-back.” A high rate of speed could catapult him right over the
obstacle. Choosing a lower rate of speed works better and also enables the
man to get closer to the obstacle before his movements are limited.
page 274
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 9-3: Even a complex object has a bounding box that is a simple rectangle.
The way around this is to use Flash’s shape-testing method of hitTest collision detection. Just testing
the shape of one object against the shape of another would be nice, but unfortunately it’s not that
simple. If using shape-test collision detection, you can test the shape of one object only against a single
point on the stage. This limitation means that you can’t test two complex shapes to see whether one
"fits inside" another in some creative way. The best that can be achieved is to check the shape of a
complex object against the center point of another object. (It doesn’t necessarily need to be the center
point, but that point is the most common one to use.)
The hitTest action still performs the collision testing, but the parameters that you provide it are
different. The syntax is as follows:
someObject.hitTest( xpoint , ypoint , shapeBoolean);
Obviously, someObject is the name of the object you’re testing for hits and should usually be the one
that’s more complex in shape, like the one shown in Figure 9-3. The xpoint and ypoint parameters
need to be replaced with numbers or variables containing an x-coordinate and a y-coordinate on the
stage. The shapeBoolean parameter needs be replaced with either true or false. Specifying true
tells Flash that you want it to use the true shape of the object specified in someObject and test to see
whether the point you specify falls anywhere on the shape. The shape in this case refers to the actual
graphic, not the bounding box surrounding the graphic. If the point you’re testing falls in a blank area of
that object, the hitTest is false.
You can also specify false for the shapeBoolean parameter, in which case Flash uses the entire
bounding box of someObject and not just its accurate shape to decide whether a collision occurs. As
with everything else in Flash, you have lots of ways to accomplish what looks like almost the same thing
here.
To see the shape-testing method of hitTest in action, copy the shape_test.fla file from the CD-
ROM onto your hard drive and open it in Flash for modification. This file contains one movie clip symbol
named Odd Shape, and an instance of it appears on the stage. This shape is the same one that is
shown in Figure 9-3. Follow these steps:
1. Create a circle on the stage with the Oval tool that has a fill color of red and a black
stroke. Use the Info panel to resize this circle to 20 by 20 pixels.
2. Select the red circle you created and press F6 to turn it into a button object with a name
of Red Circle Button.
page 275
Server-Side Flash: Scripts, Databases, and Dynamic Development
3. With the Red Circle Button still selected on the stage, press F6 again to turn it into a
movie clip symbol with the name Draggable Circle. Double-click this movie clip to get
into its editing mode and back to the button inside it that you created. Attach the
following ActionScript to the button:
4. on(press){
5. this.startDrag();
6. }
7. on(release){
8. stopDrag();
}
This code makes the Draggable Circle movie clip draggable after you click the button inside
it.
9. Return to the stage and select the instance of the Odd Shape movie clip that is there.
Give it an instance name of oddShape in the Instance panel.
10. Select the Draggable Circle movie clip and attach the following clip actions to it:
11. onClipEvent(enterFrame){
12. if(_root.oddShape.hitTest(this._x,this._y,true)){
13. _root.output=true;
14. }
15. else{
16. _root.output=false;
17. }
}
18. Using the Text tool, create a dynamic text field on the main timeline and enter output in
the Variable text box in the Text Options panel. Make sure that the Border/Bg check box
is checked. Place the field anywhere that looks convenient.
19. Use the Character panel to choose a black text color and a font size of 16 for the text
field.
Test the movie in Flash or in your browser and click the red button to start dragging it around the stage.
As you approach the odd-shaped object, the output dynamic text field you created shows a value of
false. Only if the center point of the red circle touches any part of the graphic of the odd shape does
the output field display true. Figure 9-4 shows the shape hitTest statement finally evaluate to true.
On the CD- The completed file is available on the CD-ROM as
ROM shape_test_complete.fla if you have any problems.
page 276
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 9-4: Only if the center of the circle crosses a part of the graphic does the hitTest evaluate to true.
In the following example, we choose this._x and this._y on the Draggable Circle movie clip as the
two points to check for in the hitTest statement and specify true for the shapeBoolean parameter:
if(_root.oddShape.hitTest(this._x,this._y,true)){
To see what the difference is if bounding box detection is used instead of shape detection, just change
the value true at the end of the hitTest statement on the Draggable Circle movie clip so that it is
false, as follows:
if(_root.oddShape.hitTest(this._x,this._y,false)){
Test the movie again and you see that, anytime the center point of the circle crosses into the
rectangular bounding box area surrounding the odd shape, the output text field shows true. Figure 9-
5 shows this new movie in action.
page 277
Server-Side Flash: Scripts, Databases, and Dynamic Development
5. }
6. }
7. onClipEvent (mouseUp) {
8. this.stopDrag();
}
9. Test the movie in Flash or in your Web browser. Place your mouse anywhere over
the blue graphics contained within the Odd Shape movie clip and press and hold your
mouse button to start dragging the clip around!
Notice that you did not turn this movie clip into a button or put a button inside it. You basically just used
hitTest to figure out whether the mouse pointer was anywhere over the graphical shape of the Odd
Shape movie clip when you clicked the mouse button. If it was, you could drag the clip around. If you
clicked in the blank area in between the spokes of the Odd Shape movie clip, no dragging would occur
because the mouse pointer was not touching the shape.
You can very easily change the scripting, though, so that you could click anywhere within the bounding
box of the Odd Shape movie clip and start dragging it around. Just return to the Flash authoring
environment and change the Boolean parameter in the hitTest code in the onClipEvent for the Odd
Shape movie clip to false, as follows:
if(this.hitTest(_root._xmouse,_root._ymouse, false)){
Test the movie again and place your mouse any place in the blank areas between the spokes of the
oddly shaped clip. Hold down your mouse button and you can immediately begin dragging the clip
around. Figure 9-6 shows this happening.
This whole method of initiating drags is more convenient because you don’t need to create an extra
button (or invisible button) to stick inside of the movie clips that you want to be draggable. And
whenever you do put a button inside of a movie clip symbol to initiate dragging, that button is present
and active across all the instances of that clip you place on the stage. Because in this example we used
an onClipEvent action that is unique to each instance, you can configure different instances of the
same symbol to be draggable or not draggable on a per instance basis.
Figure 9-6: By using hitTest with the shape parameters, you can drag movie clips around without using a
button.
page 278
Server-Side Flash: Scripts, Databases, and Dynamic Development
Tip Another advantage of using hitTest with an onClipEvent is that, when you’re
checking to see whether the user is clicking the particular movie clip you attached
the code to, the user doesn’t see the hand symbol appear the way it would
normally in Flash if the user were hovering over a button. This mimics the more
traditional operating-system click-and-drag capability of Windows or a Mac
operating system. (If you go to drag a folder around your desktop, a silly hand
doesn’t appear as you roll over it.) You can now create the same kind of
environment inside Flash.
Figure 9-7: The basic layout of the timeline for the man_on_circletrack.fla file.
page 279
Server-Side Flash: Scripts, Databases, and Dynamic Development
"Establishing freedom of movement.") The actions are identical to that of the man
walking around in the earlier examples of this chapter except that the angleChange
variable is changed to reflect a value of 5 instead of 10 so that the little man can’t turn
as fast on the tight circular track.
3. Test the movie and use the four arrow keys on your keyboard to walk the little man
around the screen. Notice that he currently has free reign to run amok all over
everything and is blatantly ignoring the circle track he’s supposed to be confined to.
4. Return to the Flash authoring environment and select the little man. View his clip
actions in the Actions panel and notice that the bottom section of the code where we
were doing obstacle collision detections earlier in this chapter is now just the following
commented code:
5. //If the man is not within the circle
6. //track, move him back to where he was
//
7. Change this block of code to the following:
8. //If the man is not within the circle
9. //track, move him back to where he was
10. if(!_root.circleTrack.hitTest(this._x,this._y,true)){
11. this._y-=ymove;
12. this._x-=xmove;
}
13. Test the movie in Flash again and use your four arrow keys to move the little man
around the track. You see that he is now confined to the circle track and cannot
venture beyond its bounds! The completed file is available on the CD-ROM as
man_on_circletrack_complete.fla.
To understand what these steps are doing, look at the code you added containing the if and hitTest
statement. The key to the whole statement is the exclamation point (!), which stands for the logical
operator NOT, at the very beginning of the if evaluation. What we’re saying in this statement is that we
do want the man to be touching the shape of the circle track. If by chance he’s not touching the track
after ActionScript moves him somewhere, he’s out-of-bounds and needs to be sent back to where he
was. This statement tests the little man’s x- and y-coordinates to see whether they reside anywhere
inside the graphical shape of the circle track.
This example is really just obstacle detection in reverse. In the earlier examples in this chapter, the goal
is to keep the little man away from any objects on the stage, and if he happens to move to a position
where he is touching one of them, the ActionScript sends him right back to where he was before the
screen had a chance to update. In the current example, the goal is to keep the little man on top of
another object ( in this case, the circle track. If ActionScript figures out that he’s not touching the shape
of the track after making a movement, he gets sent back to where he was, which is someplace still
touching the track.
To take this example one step farther, suppose that you were creating a game where an object needed
to remain on a path and breaks or gaps that needed to be bridged somehow were in that path. The
following steps create a break in the circle track, along with a bridge that can be dragged over the gap
to make it passable.
On the CD- Copy the file man_on_circletrack_complete.fla to your hard drive and open
ROM it in Flash for modification. You may also use the file you created in the last
example if you still have it available.
page 280
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 9-8: The circle track is split in half, and a gap has been created between the sections.
3. Still inside the editing mode of the Circle Track movie clip, use the Rectangle tool with
a fill and stroke color of black to draw a rectangle somewhere on the stage.
4. Select this rectangle and use the Info panel to resize it to approximately 95 pixels
wide by 52 pixels high. With the rectangle still selected, press F6 to turn it into a
movie clip with a symbol name of Bridge. You use this bridge to close the gap
between the sections of the track.
5. While still inside the editing mode for the Circle Track movie clip that now contains the
bridge, select the bridge and add the following clip action to it:
6. onClipEvent (mouseDown) {
7. if(this.hitTest(_root._xmouse,_root._ymouse, true)){
8. this.startDrag();
9. }
10. }
11. onClipEvent (mouseUp) {
12. this.stopDrag();
}
This code should be very familiar from a few pages back, in the section “Turning movie clips
into buttons.” What we’ve done here is make this Bridge movie clip draggable whenever
someone clicks and drags on it.
13. Position the Bridge movie clip somewhere in the white area of the stage so that it’s
not touching the blue track.
14. Return to the main timeline and position the little man movie clip so that he is
touching and well inside one of the two track sections. Test your movie in Flash or in
your browser.
page 281
Server-Side Flash: Scripts, Databases, and Dynamic Development
As you move the little man around by using the arrow keys on your keyboard, you see that he stops
whenever he reaches the white area separating the pieces of the track. To save the day and let the little
man cross over, just move your mouse pointer over the black “bridge” movie clip and click it to drag it
into position over the gap in the track. As soon as you do so, you should be able to use your arrow keys
to let the little man cross over the bridge to the other side of the track. Figure 9-9 shows the little man
happily making his way across the bridge.
On the CD- This file is available on the CD-ROM with the extremely long filename
ROM man_on_circletrack_bridge_complete.fla.
The little man can do this because the code attached to his movie clip with an onClipEvent is
checking to make sure that he is always touching the Circle Track movie clip. That means that any
graphic object inside the Circle Track clip (including other movie clips such as the bridge) is fair game to
be considered as part of the shape of the track.
The code presented in this section is transferable to any application you may need to use it for. You
should be able to see by now where you need to make modifications, such as making sure that you
always place the correct instance name right before your hitTest statement. The applications for this
kind of code in gaming are endless. Try creating your own track in a wild-and-crazy shape. You also
could create bridges that move in and out by themselves. You are limited only by your imagination.
Figure 9-9: The little man crosses over the bridge that was dragged into place to fill the gap in the track.
Summary
Collision detection combined with movement of an object is a great way to create obstacles for gaming
or dynamic development projects. As you saw in the last section, collision detection can be applied in
unique ways to turn movie clips into buttons or to constrain an object to the shape of a certain unique
graphic area. Most of the code and examples in this chapter and the last are easily adaptable to your
gaming projects. These concepts and code pieces can help to fill in the missing links in the games
you’ve been creating and plan to create as well as help you think about your game construction and
organization in new and unique ways. Happy gaming!
page 282
Server-Side Flash: Scripts, Databases, and Dynamic Development
eBusiness sites that had these elements were found to be more successful and survived at a far higher
rate than those sites that did not. By considering each of these elements, we have a clear goal in mind
when deciding what needs to be included in the Flash movie and site.
page 283
Server-Side Flash: Scripts, Databases, and Dynamic Development
Attract
Attraction means that the viewer is captivated by what you place on the Web page. In large part, the
process of attraction depends on the customer’s interest. Younger audiences may be interested in
action-adventure computer software, while older audiences may seek out stock portfolio software.
Therefore, the first rule of attraction is to consider your audience. Begin with what your target audience
finds interesting and go from there.
One of Flash’s best qualities is its capability to provide eye-catching animation with sound to add
interest to a site’s product’s and services. But animation also can annoy the viewer, so you must be very
judicious in your choice of animated objects and sound. The following are some different types of
animation and sound that you can render in Flash:
The big show: Some sites provide lots of graphics and sound that is very exciting the
first time it is viewed. The strong point of this kind of attractive movie is that people
often tell their friends, “You gotta see this URL!” The big show can, however, detract
from your product or service, and after being viewed once or twice, it becomes more
of a hindrance than an attraction. To successfully have a big show attraction, provide
a “skip intro” option or even consider planting a cookie after the viewer has seen it
once so that he or she doesn’t need to see it again. Make sure that you don’t lead the
viewer back to the big show in your links.
Little animations and surprises: To add fun, whimsy, and excitement to a site, you
can attract viewers with little animations that surprise the viewer and perform a
function as well. The simplest example of this approach is the rollover — a Flash
object that changes as the mouse passes over it. By putting in a few unexpected
twists and turns in the basic rollover, you can add more interest to the site. For
example, one developer’s site included an invitation to launch a page from the
developer’s portfolio. After the viewer clicked the Launch button, a little rocket icon
took off to the background sound of a NASA countdown. This rollover provided a little
fun, didn’t get in the way, and gave the viewer something to grin about while the page
was launching.
New Age float: For some products or services, a less dramatic but very effective way
to use movement to get the viewer’s attention is to use slow fade-ins and fade-outs to
float different images on-screen. Accompanied by soothing New Age music, such
pages promise peace of mind with a product or service.
Jump the facts: A final way to attract viewers is to have a key product or service
featured. An immediate presentation that is animated and then stops draws attention
to the elements that piqued the viewer’s interest in visiting the site in the first place.
Engage
To engage viewers, give them something to do. Often in real estate sites, the viewer is provided with a
calculator to calculate monthly payments based on interest rates and the purchase price of the house.
When using the calculator, the site visitor is subtly encouraged to look at other properties and make
similar calculations. Little quizzes, puzzles, or other engaging elements on a Web site that provide an
activity for viewers can be important in keeping them at the site.
Relate
Relating to an audience, like attracting an audience, requires that you know your audience. By providing
information and special tools, perhaps an online newsletter, you can better make a connection between
your business and your customers. E-mail is another good way to relate to customers. Usually you can
add an e-mail feature with a contact form. A contact form is simple to make with PHP and is a good tool
to have on your site.
Learn
You can gather information from your site’s viewers in many ways. Along with contact forms, survey
forms can prove invaluable. Surveys should be relatively short and focused on what your company can
provide in services and products. You may discover needed services that you never thought about by
using a survey.
page 284
Server-Side Flash: Scripts, Databases, and Dynamic Development
Another tool for learning about your customers is to track the buttons and links on your site. Whenever
the visitor clicks a button, you can include a little ActionScript to fire off a PHP script that increments a
MySQL database to record the click. In this way, you can learn what visitors do and do not do when
they visit your site. Such feedback helps you better understand and serve your customers.
Retain
The final important element of the value bubble is retention. Your site should have mechanisms that
make your customers want to come back. A cookie placed on the visitor’s computer can be turned into a
greeting with the visitor’s name. Automatic e-mails, online calendars announcing new products or
services, news about your company, and message boards or online chat rooms with dialogue between
customers provide ways to retain customers.
Your site needs to be designed around your customer and the products or services you have. Some
products must be shipped to the customer, such as toys and books. Other products, such as software,
can be downloaded, and some products provide access to information on the Web.
Products
The basic distinction between products is whether they must be shipped. Very different front-end and
back-end decisions must be made depending on what has to be done with a product to get it to the
customer.
Shipped
Shipped products imply some finite inventory and a location for shipment. As products are ordered, the
orders can be attached to a database that keeps track of the inventory of the product. After an order
ships, the inventory database should be decremented by the number of ordered items. Similarly, a
shipping address is required, so the site designer needs to consider having information for both a billing
and a shipping address.
Online
Life would be so much simpler for the designer and the client if all products could be dealt with online.
Products that can be downloaded save the expense of shipping and having both a billing and shipping
address. But downloaded products can be sent to a different e-mail address than the e-mail address
from which the product is ordered; therefore, you should consider having an alternative e-mail address
for the online products that can be downloaded.
A second type of online product is access to information. Usually if the product is a general type of
information, such as expertise on investments or an online magazine, the product is standardized even
though the user can select from a variety of choices. No shipping is required, but the designer still
needs to include forms for user information for billing purposes.
Services
One of the most ubiquitous services provided over the Internet is support service. Usually, this kind of
service is packaged as part of another service. Both JTLNet and HosTek, whose hosting services are
provided on a trial basis with this book, include extensive support service modules. Both FAQs
(Frequently Asked Questions) and e-mail contact with responses to specific questions are provided.
Online
When information is gathered to meet a specific online request, as opposed to being provided as an
existing general information product, such as an online magazine, the information is considered a
service because the information must be generated uniquely for a request. All the service requirements
can be handled online in such situations, so the site developer must include clear e-mail contact with
the client as well as phone or FAX numbers.
Face-to-face
page 285
Server-Side Flash: Scripts, Databases, and Dynamic Development
Both Dell and Gateway provide maintenance contracts with their computers, and any computer repair
must be done on-site. If such on-site service is part of a contract, a site may need three addresses: the
ship-to address (when the computer is originally purchased), the bill-to address, and the repair-site
address. For example, a company with a central-receiving office may order a product from one location,
have it shipped to central receiving, and then send it to a satellite office where the product is used.
Billing
Any billing involving a credit card transaction requires a special module. We don’t provide a module for
credit card payment in the project in this chapter because we were concerned that someone would set it
up and attempt to do online credit card business without the special security required. Several
companies, many of which are associated with hosting services, provide online credit card modules that
you can seamlessly include in your Flash site. Early on in developing your eBusiness site, contact your
hosting service or one of the secure credit card processing companies, such as CyberCash
(www.cybercash.com) or LinkPoint (www.linkpoint.com). See what modules they provide for
payment. If the module cannot be integrated into Flash, you can link to an HTML page for the credit
card information and then come back to the Flash module.
For subscription products and services, the designer needs to include a start date and an ending date
that can be stored and checked daily on a database. Other information can be based on a “pay-per-
view” system for users who need the information only occasionally, and the billing for this type of site
works the same as any one-time product site.
page 286
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-1: A clean and simple frame is the initial view of the site.
The stage is reset to 650 by 400 pixels in the Movie Properties dialog box. (Choose Modify → Movie to
access.) The color palette is a calm one using muted greens, gray, black, and white (see Table 10-1).
The colors are selected to provide a comfortable environment for the viewer, and although they do not
leap out at the viewer, they are effective for attracting attention without distracting from the site.
Table 10-1: Color Palette for DesignShop.fla
Colors R Value G Value B Value
A 99 CC 66
B 66 66 66
C 00 99 33
D 99 99 66
E (White) FF FF FF
F (Black) 00 00 00
At the base of the project is a simple line of text with a line above it and a thick black bar along the
bottom. The text is a graphic with the Alpha reduced to 15 percent. It was created with a 35-point
Verdana font in black with the AV set to 30. The bar at the bottom has the dimensions of W=650, H=57,
and the line above the text is a black line with a stroke of 1.
page 287
Server-Side Flash: Scripts, Databases, and Dynamic Development
After you complete the Background layer, lock it. The next step is to create the drop-down menus on
two layers: the Label Buttons layer and the Menus layer.
Each of the menus has a button on top of the drop-down menus. Use the following steps to create four
buttons:
1. Using a 10-point bold Verdana font, type the word design.
2. Select the text and press the F8 key to open the Symbol Properties dialog box.
Choose Button as the Behavior, and name it Design. Click OK.
3. Double-click the button and, in the Symbol Editing mode, place a keyframe in each of
the three frames with no keyframe.
4. Click the Hit frame and then use the Rectangle tool to place a rectangle with the
dimensions of W=79, H=16 over the word design. This step broadens the hit area to
the width of the menu bar of the drop-down windows.
5. Repeat steps 1 through 4 using the words products, information, and contact.
6. Drag an instance of each of the four buttons to the stage and, in the Object Actions
panel, add the following ActionScripts to the indicated buttons. Each script fires off a
movie clip to drop one menu and close the others.
Design button:
on (rollOver) {
_root.dropD.gotoAndPlay(1);
_root.dropP.gotoAndStop(1);
_root.dropI.gotoAndStop(1);
_root.dropC.gotoAndStop(1);
}
Products button:
on (rollOver) {
_root.dropP.gotoAndPlay(1);
_root.dropD.gotoAndStop(1);
_root.dropI.gotoAndStop(1);
_root.dropC.gotoAndStop(1);
}
Information button:
on (rollOver) {
_root.dropI.gotoAndPlay(1);
_root.dropP.gotoAndStop(1);
_root.dropD.gotoAndStop(1);
_root.dropC.gotoAndStop(1);
}
Contact button:
on (rollOver) {
_root.dropC.gotoAndPlay(1);
_root.dropP.gotoAndStop(1);
_root.dropI.gotoAndStop(1);
_root.dropD.gotoAndStop(1);
}
After you finish with the buttons, put them aside on the stage. In the next set of procedures, you place
them on the menus.
page 288
Server-Side Flash: Scripts, Databases, and Dynamic Development
The primary navigation occurs in the four drop-down menus. Each menu is a movie clip with two or
more buttons within the movie clip. As the menus drop down, they reveal the buttons within each menu
category. All the menus are constructed using similar parts and techniques, so we go through the steps
in making one menu and point out the steps for the others. All the buttons in the menu contain
ActionScript to play different parts of the main movie. Just follow these steps:
1. Using Color D from the movie palette, draw a rectangle with the dimensions W=81,
H=16. Select it and press the F8 key to open the Symbol Properties dialog box.
Select Graphic for the Behavior, enter open in the Name box, and click OK.
2. Using Color A from the movie palette, create a rectangle with the dimensions W=80,
H=95. Select it and press the F8 key to open the Symbol Properties dialog box.
Select Graphic for the Behavior, enter bg (for background) for the Name, and click
OK.
3. Choose Insert → New Symbol from the menu bar. Select Movie Clip for the Behavior
in the Symbol Properties dialog box. Enter drop for the Name.
4. While still in the Symbol Editing mode, add three layers to the existing layer for a total
of four layers. Use the names buttons, fill, sides, and bar from top to bottom.
5. Click column 10 and drag the mouse downward to select all four layers. Press the F5
key to add frames out to the tenth column. In the first frame of the Fill layer, place a
stop(); action using the Frame Actions panel. Likewise, put a stop(); action in the last
frame of the Side layer.
6. While still editing the Drop movie clip instance, select the Fill layer and drag an
instance of the Bg symbol onto the stage. Select the Bar layer and place an Open
instance over the top of the Bg instance. (Because the Open instance is on a lower
layer than the Bg instance, it will appear under the Bg instance.) Select the Bg
instance and, in the Info panel, change the H value to 1. Draw two lines along either
side of the Open instance in the Sides layer. Figure 10-2 shows the position of the
line in a 400 percent enlargement of the stage.
Figure 10-2: The lines on either side of the Open instance (400 percent magnification) show
the details of the menu in the closed position.
page 289
Server-Side Flash: Scripts, Databases, and Dynamic Development
7. Add keyframes in the Fill, Sides, and Bar layers in Frames 4, 7, and 10. Select all the
keyframes in the Fill and Bar layers and, using the Frame panel, add Motion Tweens.
Select all the keyframes in the Side layer and add Shape Tweens.
8. Add a keyframe in Frame 10 of the Buttons layer.
9. To achieve a “bounce” effect of the menu dropping and then popping up momentarily
and then down again, you must change the dimensions of the Bg instance several
times. Click Frame 4 in the Fill layer and then change the dimensions of the Bg
instance to W=80, H=95. Click Frame 7 of the Fill layer and change the Bg instance
to the dimensions W=80, H=64. Click Frame 10 of the Fill layer and change the
dimensions of the Bg instance to W=80, H=80.
10. Along with the Bg instance, you also must move the Open instance. Click the Bar
layer and, with a starting Y position of -9, click Frame 4 and move the vertical position
to Y=87 using the Info panel. On Frame 7, move the vertical position of the Open
instance to 56. On Frame 10, move the Y position of the Open instance to 72.
11. Click the Side layer. In the Info panel, you should see that H=16 for both lines. Click
Frame 4 and change the H value to 110 for both lines and then align them vertically
with the top and bottom of the Bg and Open instances. Repeat the process in Frame
7, changing the H value to equal 80. In Frame 10, change the H value to equal 95.
At this point, your menu should move up and down with a drop-and-bounce effect. Move the playhead
left and right to make sure that all the menu parts coordinate. Figure 10-3 shows how the menu looks
with the onion skin enabled in the FLA file.
Figure 10-3: After the menu object is complete, it should drop down, bounce, and settle in the extended
position.
The final thing that you must do is to provide an instance name to the Drop movie clip. Click Scene 1 to
go to the main timeline, select the Drop movie clip, and in the Name box of the Instance panel, type the
instance name dropD. Each of the other three menu movie clips have instance names of dropP, dropI,
page 290
Server-Side Flash: Scripts, Databases, and Dynamic Development
and dropC. The capital letter at the end of the instance names reflects the Design, Products,
Information, and Contact names of the menus. After you complete the first Drop movie clip, create three
more identical movie clips with the names identical to the instance names: dropP, dropI, and dropC.
Figure 10-4: Place the submenu buttons on the extended menus in the Symbol Editing mode of the Drop
movie clips.
Each menu button contains ActionScript. The buttons on the Design menu contain the following code:
Banners:
on (release) {
_root.gotoAndStop(2);
this.gotoAndStop(1);
}
Flash:
on (release) {
_root.gotoAndStop(4);
this.gotoAndStop(1);
}
Sites:
on (release) {
_root.gotoAndStop(6);
this.gotoAndStop(1);
page 291
Server-Side Flash: Scripts, Databases, and Dynamic Development
The Action Script for the buttons on the Products menu is as follows:
Downloads:
on (release) {
_root.gotoAndStop(8);
this.gotoAndStop(1);
}
Books:
on (release) {
_root.gotoAndStop(10);
this.gotoAndStop(1);
}
The Information menu has two buttons with the following code:
FAQ:
on (release) {
_root.gotoAndStop(12);
this.gotoAndStop(1);
}
About us:
on (release) {
_root.gotoAndStop(16);
this.gotoAndStop(1);
}
The code for the two buttons on the Contact menu is as follows:
Contact form:
on (release) {
_root.gotoAndStop(14);
this.gotoAndStop(1);
}
Email:
on (release) {
getURL ("mailto:[email protected]");
this.gotoAndStop(1);
}
After you create the submenu buttons, place them in the Symbol Editing mode of the appropriate Drop
menu movie clip. Select the button layer, move the playhead to the last frame, and then drag each of
the submenu buttons to the open frame, as you can see in Figure 10-4.
The Shopping Stops layer is a series of alternating keyframes and blank keyframes. Each keyframe is
the target of one of the submenu selections. (The blank keyframes provide a less crowded layer,
making selecting the substantive keyframes while you are editing easier.) Place keyframes in Frames 2,
4, 6, 8, 10, 12, 14, 16, 18, 20, and 22 and place blank keyframes in Frames 3, 5, 7, 9, 11, 13, 15, 17,
19, and 21.
Create two button symbols named add and subtract. These buttons should have these dimensions:
H=17, W=17. To create the buttons, draw a black circle with a green (Color C) stroke. Use the Line tool
to draw a white plus sign on one button and a minus sign on the other. Don’t use the Text tool to do this
because the border from the text box makes the object awkward to adjust.
page 292
Server-Side Flash: Scripts, Databases, and Dynamic Development
Banner frame
The first stop at Frame 2 is the banner. An animated Banner movie clip moves text and a ball over a
gray rectangle. Below the banner are two labels for services and their costs, as shown in Figure 10-5.
Figure 10-5: An animated banner provides an example of the service product, and a set of four buttons
enables the customer to add the service to the floating Cart Recorder.
At the heart of the movie are buttons that keep track of what a customer purchases. A floating Cart
Recorder with the text field variable name total keeps an ongoing record of what the customer
selects. The buttons in the different frames in the Shopping Stops layer contain the variables that record
what is selected and what is deselected. All the subtract buttons require a conditional statement to
make sure that the user does not move the total below zero. The variables ending in T are totals for
each product or service. Here is the code:
Single Animated Scene Add:
on (release) {
banA = 500;
banAT += banA;
sum += banA;
_root.calc.total = sum;
}
Single Animated Scene Subtract:
on (release) {
banA = 500;
page 293
Server-Side Flash: Scripts, Databases, and Dynamic Development
banAT -= BanA;
if (banAT<0) {
banAT = 0;
}
sum -= banA;
if (sum<0) {
sum = 0;
}
_root.calc.total = sum;
}
Additional Scenes Add:
on (release) {
banB = 450;
banBT += banB;
sum += banB;
_root.calc.total = sum;
}
Additional Scenes Subtract:
on (release) {
banB = 450;
banBT -= banB;
if (banBT<0) {
banBT = 0;
}
sum -= banB;
if (sum<0) {
sum = 0;
}
_root.calc.total = sum;
}
Flash frame
Frame 4 contains a movie clip that appears in parts in a two-second clip. Figure 10-6 shows the Flash
Page movie clip in the Symbol Editing mode. Little sound spots emphasize the three nonfunctional
buttons that appear along the top of the movie clip. Finally, a separate movie clip made up of a spinning
snowflake continues after the Flash Page movie clip stops.
page 294
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-6: A movie clip puts together the parts of a Flash movie before the viewer’s eyes.
The following code shows how the Add and Subtract buttons keep track of the selections on the page:
Flash Page Add:
on (release) {
flpg = 1000;
flashT += flpg;
sum += flpg;
_root.calc.total = sum;
}
Flash Page Subtract:
on (release) {
flpg = 1000;
flashT -= flpg;
if (flashT1<0) {
flashT1 = 0;
}
sum -= flpg;
if (sum<0) {
sum = 0;
page 295
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
_root.calc.total = sum;
}
Site frame
Frame 6 is similar to the Flash frame movie. A movie clip quickly presents a growing series of
rectangles to represent the elements in a Web site and stops. Sound effects from the Sound Library
(which you access by choosing Window → Common Libraries → Sounds) provide additional interest.
Figure 10-7 shows the movie in the Symbol Editing mode:
Figure 10-7: This movie clip assembles the parts of a Flash movie in front of the viewer.
The Add and Subtract buttons use the following code to keep track of a user’s selections and deletions:
Site Design Add:
on (release) {
siteDev = 1500;
siteT += siteDev;
sum += siteDev;
_root.calc.total = sum;
}
Site Design Subtract:
on (release) {
page 296
Server-Side Flash: Scripts, Databases, and Dynamic Development
siteDev = 1500;
sum -= siteDev;
if (sum<0) {
sum = 0;
}
siteT -= siteDev;
if (siteT<0) {
siteT = 0;
}
_root.calc.total = sum;
}
Downloads frame
Frame 8 represents a departure from the other frames in that no movie clips are used and both products
are free. And because downloads can be reproduced infinitely, you don’t need to subtract from an
inventory or user selection. The Cart Recorder shows No Charge, but the ongoing total is not affected
because the total has been recorded in the sum variable.
In eBusiness, downloads play an important role of attracting customers who may visit the site often just
to get the free downloads. If they do want to make a purchase of products or services, the goodwill built
up leads the customer to the site. (That’s the theory anyway.) Figure 10-8 shows the simple features
presented in the Downloads frame.
page 297
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-8: Simple choices with no charge make the Downloads frame a popular one.
The buttons use the getURL() action to connect the user to the downloads. One of the features on the
site is included as a download.
Preloader Add:
on (release) {
_root.calc.total = "No Charge";
getURL ("http://www.yourDomain.com/downloads/preload.fla");
}
Floating Add:
on (release) {
_root.calc.total = "No Charge";
getURL ("http://www.yourDomain.com/downloads/floatcart.fla");
}
Books frame
Frame 10 illustrates a situation where the product incurs shipping charges and requires inventory
tracking. The frame itself is quite simple, as shown in Figure 10-9, but the buttons have a bit more
ActionScript than what has previously been shown.
page 298
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-9: Because the listed items are shipped products, the ActionScript in the buttons requires a bit
more code.
Backside Add:
on (release) {
bof = 35;
bofInv += 1;
ns += 1;
bofT += bof;
sum += bof;
_root.calc.total = sum;
}
Backside Subtract:
on (release) {
bof = 35;
bofInv -= 1;
bofT -= bof;
ns -= 1;
bocT -= boc;
if (bofT<0) {
page 299
Server-Side Flash: Scripts, Databases, and Dynamic Development
bofT = 0;
}
sum -= bof;
_root.calc.total = sum;
}
Born Add:
on (release) {
boc = 40;
bocInv += 1;
ns += 1;
bocT += boc;
sum += boc;
_root.calc.total = sum;
}
Born Subtract:
on (release) {
boc = 40;
bocInv -= 1;
bocT -= boc;
ns -= 1;
if (bocT<0) {
bocT = 0;
}
sum -= boc;
_root.calc.total = sum;
}
Gothic Add:
on (release) {
gcbb = 5;
gcbbInv += 1;
ns += 1;
gcbbT += gcbb;
sum += gcbb;
_root.calc.total = sum;
}
Gothic Subtract:
on (release) {
gcbb = 5;
gcbbInv -= 1;
gcbbT -= gcbb;
ns -= 1;
if (gcbbT<0) {
gcbbT = 0;
}
sum -= gcbb;
_root.calc.total = sum;
page 300
Server-Side Flash: Scripts, Databases, and Dynamic Development
}
In the buttons’ ActionScript, both a shipping variable (ns) and inventory variables (xxxInv) are added.
The shipping variable is the same for all the products because a standard shipping cost is established
for each item. The inventory variables, though, must be unique for each of the three items. If we had
more item selections, array variables would be more efficient to use.
FAQ frame
In any eBusiness, a FAQ page saves time, money, and aggravation. Actual questions from customers
and anticipated questions that may arise in site testing should be included. Make the questions concise
and the answers clear so that the reader can quickly see the focus of the question and the solution in
the answer. Think of FAQ pages as customer service pages. All you need to do is to place a blank
keyframe in Frame 11 and a regular keyframe in Frame 12 and then put your FAQs in a static text field.
Figure 10-10 shows an example of what a FAQ page looks like.
Figure 10-10: FAQ pages should be clear, concise, and informative in an eBusiness site.
Contact frame
Frame 14 has a contact form that viewers can fill out even if they don’t want to purchase anything. From
such contact forms, a business both engages viewers and learns from them. Site visitors who use the
contact form should receive an automatic e-mail response from a server-side script. If the comments
require specific information, you can use a follow-up e-mail.
The Contact frame is made up of several input text fields and a button to initiate a PHP script and send
the variables from Flash to the script. Table 10-2 shows the several input text fields and their associated
variable names. The input fields are arranged as shown in Figure 10-11.
page 301
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-11: Comment forms help engage customers and establish a relationship between the company
and the customer.
To send the information in the form, you need some kind of event and event handler. A simple Send
Form button works well. Create the button by using the image shown in Figure 10-11 and add the
following ActionScript, substituting your own URL or IP address:
page 302
Server-Side Flash: Scripts, Databases, and Dynamic Development
on (release) {
loadVariablesNum ("http://www.yourDomain.com/PHP/contact.php", 0, "GET");
}
Tip The GET method seems to work best with Flash and PHP. If you are using ASP,
we suggest using the POST method.
About Us frame
People like to know something about the company they’re doing business with, and a short “About Us”
notice helps them feel more comfortable with an eBusiness. Many e-commerce sites, such as Barnes
and Noble Bookstores, were brick-and- mortar businesses for years before the advent of the Internet, so
they were well-known when they launched their online bookstores. Other companies, such as
Amazon.com, were eBusinesses from the beginning, and they had to tell people more about themselves
so that customers could get used to the idea of shopping from an online entity without a storefront
counterpart. Figure 10-12 shows how the About Us feature was added to the site.
Figure 10-12: The About Us page helps customers get to know the business they are dealing with over the
Internet.
page 303
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-13: The first part of check out obtains the billing/shipping information.
The Visa and MasterCard buttons are generic examples of selecting a credit card. As each button is
clicked, an x appears in the adjacent text field to identify the card of choice. The buttons are instances
of simple button symbols. Open the Text Options panel and create two small dynamic text fields next to
the Visa and MasterCard buttons. In the Variable box of the Text Options panel, enter visa as the
variable name for the text field next to the Visa button and mc for the variable name next to the
MasterCard button. Use the following scripts:
Visa button:
on (release) {
visa = "x";
mc = "";
}
MasterCard button:
on (release) {
visa = "";
mc = "x";
}
The only other button on the page is one that jumps to the final Check Out frame. Because the final
check out is a necessary sequence, the button was placed on the scene rather than on one of the
menus. (Notice that the frame goes back to Frame 18 rather than forward.)
Proceed to final check out button:
on (release) {
page 304
Server-Side Flash: Scripts, Databases, and Dynamic Development
_root.gotoAndStop(18);
}
To move the floating Cart Recorder movie clip to the middle of the text fields, Frame 18 contains the
following script:
_root.calc._x=280;
_root.calc._y=215;
The instance name of the Cart Recorder movie clip is calc, so moving the object requires no more
than specifying the desired coordinates by changing the _x and _y properties.
The button is an instance of a button symbol with the name Confirm order and the following script:
on (release) {
_root.calc._x = 40;
_root.calc._y = 60;
loadVariablesNum ("http://www.yourDomain.com/PHP/confirm.php", 0, "GET");
gotoAndStop (22);
}
The script hooks up with the PHP script that takes care of the back-end work with the order and then
goes to and stops at the final frame for the order. The script also puts the floating calculator into the
upper right hand corner of the stage to get it out of the way. Figure 10-14 shows the general layout of
the stage.
page 305
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-14: The final checkout process presents the customer with information about purchases and a
chance to confirm the order.
page 306
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-15: The confirmation page is made up of two dynamic text fields. The smaller one delivers a
confirmation signal, and the larger one displays the information generated by the ActionScript in the frame.
The Floating Calculator layer contains a movie clip used to display the total amount a customer is
spending as services and products are added and subtracted from the shopping cart. The name Cart
Recorder suggests the dual nature of the object: It’s a shopping cart as well as a calculator that records
the current amount in the shopping cart. The following steps show how to create the Cart Recorder:
1. Create a new symbol by choosing Insert → New Symbol from the menu bar. Select
Movie Clip for the Behavior and type Calculator for the Name.
2. In the Symbol Editing mode, create two layers, named text field (top) and Calculator
and label (bottom).
3. Click the bottom layer and use the Rectangle tool to draw a gray (Color B on the
movie’s palette) rectangle with the dimensions W=72, H=73.
4. Using a 10-point white Verdana font in a Static text field, type Cart Recorder and
place the text in the horizontal and vertical center of the rectangle. Lock the bottom
layer.
5. In the top layer, create a dynamic text field and place it in the horizontal center of the
gray rectangle above the Cart Recorder label. (See Figure 10-16.) In the Text Options
panel, type the name total in the Variable box.
page 307
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 10-16: A 200 percent view of the floating calculator shows it to be a movie clip with a
dynamic text field associated with the total variable name.
6. Click Scene 1 to return to the main timeline. Select the Calculator movie clip and, in
the Instance panel, type the name calc. With the Calculator movie clip still selected,
enter the following ActionScript in the Frames Actions panel. This script enables the
user to drag the object anywhere on the stage.
7. onClipEvent (mouseDown) {
8. startDrag (this);
9. }
10. onClipEvent (mouseUp) {
11. stopDrag ();
12. }
The final object in the movie is a button in the Check Out layer. The button does two things. First, it
goes to the first stop on the check out path, calculates tax and shipping costs, and adds up everything
to calculate a grand total. But it also serves as a drop-down menu closer. If any of the menus are left
open, a rollover on the button closes them.
Create a circle with the dimensions W=47, H=47 using Color A from the palette (lighter shade of green)
for the fill and black for the 2-point stroke color. Create a button symbol from the circle. Change the fill
color to the darker green (Color C) with the playhead in the Over frame in the Symbol Editing mode of
the button. Label the button Check out, as shown in Figure 10-17, and enter the following script:
on (release) {
page 308
Server-Side Flash: Scripts, Databases, and Dynamic Development
_root.gotoAndStop(20);
tax = (_root.calc.total)*.08;
shipping = ns*1.25;
grandTotal = _root.calc.total+tax+shipping;
grandTotalS = "$"+grandTotal;
}
on (rollOver) {
_root.dropD.gotoAndStop(1);
_root.dropP.gotoAndStop(1);
_root.dropI.gotoAndStop(1);
_root.dropC.gotoAndStop(1);
}
Figure 10-17: A 200 percent view of the button and its associated script.
Summary
In developing the DesignShop.fla movie, we wanted to provide a generic eBusiness site that could
be customized to suit different objects a designer or developer may have when creating a site for a
client. Modifying the site is a matter of changing it to suit your own needs. Adding buttons and additional
submenus along with text fields to hold information should do the trick for simple sites. For sites with a
large number of products, use arrays instead of variables and remember to plan, plan, and plan.
page 309
Server-Side Flash: Scripts, Databases, and Dynamic Development
The initial setup uses the sample hosting service for PHP, JTLNet. Use your JTLNet account to set up
your database and tables with the following steps:
1. Go to the JTLNet support page for your account. For example, if your domain name is
www.yourDomain.com, you would type in
http://www.yourDomain.com/controlpanel. After entering your username
and password, you would be at the main menu of Cpanel 3.
2. Choose Advanced Menu → SQL Database to enter the mySQL page. In the Db box,
type in designShop and click the Add Db button. Now you have a database with the
name username_designShop. (JTLNet adds the username to all databases for
security reasons.)
3. When you have your new database, click on phpMyAdmin link near the bottom of the
page. (You may have to scroll down to see it.)
4. The left column contains your database name. Click the database name to display a
page with the database name on top (for example, yourDomain_designShop). Scroll
to the bottom of the page where you will see Create new table on database
username_databaseName.
5. In the Name text box, type in customer. Enter 4 in the Fields text box below the
Name text box.
6. Table 11-1 shows the values you should enter into the category. (The table also has
Index and Unique columns not used in this project.)
7. In the Table comments text box, type Basic customer info. Then click the Save
button to finish the table.
Table 11-1: Data for the Customer Table in the designShop Database
d
Fiel
e
Typ
Set
gth/
Len
es
ibut
Attr
Null
ault
Def
a
Extr
y
mar
Pri
page 310
Server-Side Flash: Scripts, Databases, and Dynamic Development
Table 11-1: Data for the Customer Table in the designShop Database
d
Fiel
e
Typ
Set
gth/
Len
es
ibut
Attr
Null
ault
Def
a
Extr
y
mar
Pri
cusID
INt
10
UNSIGNED
nt
auto_increme
(checked)
fName
char
15
lName
char
15
email
char
30
Figures 11-1 and 11-2 show how the entries should appear in the phpMyAdmin table.
page 311
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 11-1: The table creation utility provides the same column type options used in the MySQL server.
Figure 11-2: On the right side of the table utility, you can enter additional options into the table.
page 312
Server-Side Flash: Scripts, Databases, and Dynamic Development
The table creation utility in phpMyAdmin essentially does all of the query work you would do in the
MySQL server. After you have finished entering your data and have saved your new table, you can see
the MySQL code written in a dump of the table. In the left column of the phpMyAdmin utility, click the
Customer table under the username_designShop database to open the table’s page. Then scroll down
to the View Dump (schema) of Table option and click the Go button. If you entered everything correctly,
you will see output similar to that in Figure 11-3.
Figure 11-3: The table dump shows the MySQL query code that creates the table.
A total of six MySQL tables are required for the complete designShop database. In the next section, use
the values in the MySQL commands to create the remaining tables either in the phpMySQL utility or the
MySQL server.
page 313
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 314
Server-Side Flash: Scripts, Databases, and Dynamic Development
<?php
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
mysql_select_db($flashbase,$hookup);
page 315
Server-Side Flash: Scripts, Databases, and Dynamic Development
(first,last,addr,town,st,zcode,email,ac,pnum,comment)
VALUES(‘$fname’,’$lname’,’$address’,’$city’,’$state’,’$zip’,
‘$email’,’$phoneAc’,’$phone’,’$comments’)";
mysql_query($sql,$hookup);
$sendTo=$email;
$greet .= "Your comments are important to us, and as soon as we get a chance to read them, we will get
back to you.\n\n";
mail($sendTo,$subject,$greet);
?>
Caution You have to attend to details when working with PHP and contacting the MySQL
database. Be sure that you establish your username and password correctly
before putting them into the PHP file. You can have more than one username and
accompanying password, so double-check to see that they are correct. If you
forget your password, just delete the username and then re-enter it with a
password that you can use in your script.
<?php
page 316
Server-Side Flash: Scripts, Databases, and Dynamic Development
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
mysql_select_db($flashbase,$hookup);
//Customer table
mysql_query($sql,$hookup);
mysql_query($sql,$hookup);
page 317
Server-Side Flash: Scripts, Databases, and Dynamic Development
grandTotal)
VALUES(‘$banAT’,’$banBT’,’$flashT’,’$siteT’,’$bofT’,’$bocT’,
‘$gcbbT’,’$tax’,’$shipping’,’$grandTotal’)";
mysql_query($sql,$hookup);
mysql_query($sql,$hookup);
?>
Each of the four tables is treated uniquely using the same query command (for example,
mysql_query($sql,$hookup);). The only thing you have to change is the $sql variable prior to the
query command. You can then issue the command repeatedly because changing the $sql variable
changes the command’s contents.
Note You may have noticed that no customer ID field was used in setting up the
several tables that contain such a field. Because the cusID field is an
automatically incremented one, it does not need to be listed. As long as the value
list is congruent with the list of fields shown in the SQL command, the data goes
where it is supposed to go.
page 318
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 11-4: The starting stage for the Database Administrator provides three buttons.
The color palette for this Flash movie, dbAdmin.fla, is markedly different from designShop.fla, but the
colors are a relaxing collection to use to coast through the administrative record keeping in the
database. Table 11-2 shows the colors used for this project.
Table 11-2: Color Palette for dbAdmin.fla
Color R Value G Value B Value
A CC 00 33
B FF C0 33
C 59 73 C0
D 99 CC 99
E FF F3 CC
F (Black) 00 00 00
page 319
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 320
Server-Side Flash: Scripts, Databases, and Dynamic Development
3. Select Frame 2, open the Frame Actions panel, and enter the following
ActionScript. Make sure that you substitute your own URL for the one shown:
4. loadVariablesNum ("http://www.yourDomain.com/PHP/getUnFilled.php", 0);
stop();
5. In a text editor, enter the PHP script shown in Listing 11-3. Save the script as
getUnFilled.php. Place the script in the root directory or subdirectory within the
root directory used in the URL reference in step 3.
6. Insert a blank keyframe into Frame 3 by selecting the frame and pressing the F7
key.
Figure 11-5: Only the buttons and objects on the Labels layer are shown at the outset, but
the second frame reveals a text field where unfilled customer numbers appear.
Listing 11-3: The getUnFilled.php Script
<?php
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
page 321
Server-Side Flash: Scripts, Databases, and Dynamic Development
mysql_select_db($flashbase,$hookup);
$numrows=mysql_num_rows($result);
$numrows-=1;
$search="N";
$counter=0;
$newline=chr(13);
do {
$findKey=(mysql_result($result,$counter,"complete"));
if ($findKey==$search) {
$findNum=(mysql_result($result,$counter,"cusID"));
$counter++;
while($counter <=$numrows);
$unfilled="outUnfill=$finder";
echo "$unfilled";
?>
page 322
Server-Side Flash: Scripts, Databases, and Dynamic Development
The getUnFilled.php script searches for the default N in the customer ID section of the cusComplete
table. All unfilled orders have the N, so the customer ID numbers of all unfilled orders have the
necessary match and are concatenated into a variable named $finder. After all of the tables have
been searched, the variable is translated into Flash format and then echoed back to Flash.
Figure 11-6: The button fires a PHP script that takes the customer number from the input field and returns
information from the database.
With Figure 11-6 as a guide, use the following steps to complete this next section:
1. Insert a keyframe in Frame 4 of the Show Tables layer and put in a stop() script.
2. Use the Text tool to make a small input text field (use the dimensions W=42,
H=19). Select the text field, and in the Text Options panel, type in orderNum in
the Variable text box.
3. Drag a button onto the stage and position it next to the text field. Enter the
following ActionScript, substituting your own URL:
4. on (release) {
5. loadVariablesNum ("http://www.yourDomain.com/PHP/ShowOrder.php", 0,
"GET");
}
page 323
Server-Side Flash: Scripts, Databases, and Dynamic Development
6. On the Background layer, click Keyframe 4 and draw a rectangle with the
dimensions W=64, H=16. Use Color E (cream) for the fill and stroke. Lock the
Background layer.
7. On the Show Tables layer in Frame 4, type in Show Order using the Text tool
and Color A (red) in a 10-point Verdana type.
8. Use the Text tool to draw a dynamic text field with the dimensions W=348,
H=185. Center the field on the table beneath the input text field, button, and label
as shown in Figure 11-6. In the Variable box in the Text Options panel, type in
displayOrder.
9. Use a text editor to enter the PHP file shown in Listing 11-4. Then place the file
in the root directory or subdirectory in the root directory that corresponds to the
URL in step 3.
Listing 11-4: The ShowOrder.php Script
<?php
//Set up and connect
$server="localhost"; //Server name
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
$flashbase ="domainNm_designShop"; //Database name
$cus_order="cusOrder"; //Customer order table
$orderUp="displayOrder=$fullOrder";
echo "$orderUp";
page 324
Server-Side Flash: Scripts, Databases, and Dynamic Development
?>
Although the preceding PHP code may appear daunting, most of the work is formatting. After the
MySQL query, the script sets up a big array to be used as labels to describe the contents of the table.
Next, a loop examines the rows in the table until it terminates with the row corresponding with the order
number (the cusID number is used). Then a second loop (not nested) goes through the $row array.
When the script uses the MySQL query mysql_fetch_row(), the entire row is placed into an array
with the first element in the array being the first field in the row. In the cusOrder table, the first field is the
customer ID, the second field is a service order for a banner ad, and so on until the grand total owed for
the purchase, which is the last field. Because the fields in the $cOrder array correspond to the fields in
the $row array, the second loop simply concatenates the two arrays and places a carriage return
(chr(13)) at the end so that each field will appear on a separate row in the Flash display text field
(displayOrder).
Figure 11-7: Seven text fields and three buttons provide contact information, adjust the inventory, and
record completed orders.
Examine Figure 11-7 carefully prior to beginning work on this segment of the movie. Use the following
steps to complete the movie:
1. Insert a blank keyframe in Frame 5.
page 325
Server-Side Flash: Scripts, Databases, and Dynamic Development
page 326
Server-Side Flash: Scripts, Databases, and Dynamic Development
<?php
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
mysql_select_db($flashbase,$hookup);
$cusNum -=1;
$newln=chr(13);
//Customer name
$counter=0;
$row=mysql_fetch_row($result);
$email = $row[3];
page 327
Server-Side Flash: Scripts, Databases, and Dynamic Development
$counter=0;
$rowAd=mysql_fetch_row($resultAd);
$street=$rowAd[1];
$city=$rowAd[2];
$state=$rowAd[3];
$zip=$rowAd[4];
$areaCode=$rowAd[5];
$phone=$rowAd[6];
$zip;
$customerUp="&displayCus=$fullCus&phone=$phone&email=$email";
echo "$customerUp";
?>
The second PHP script (shown in Listing 11-6) handles the inventory and clears product orders. The
script uses the MySQL UPDATE command to globally update the table. That means it changes all
records in the table. The advantage of using global updates is that you can change all the records
(rows) in a table with a single command. (That’s also the danger of using global updates!) The first
UPDATE query subtracts the total number of books sold from the inventory table to provide an accurate
count of products on hand. The second UPDATE query replaces the number of books in the inventory
counter in the cusComplete table with zeros so that the same products will not be counted more than
once.
Listing 11-6: The inventory.php Script
<?php
page 328
Server-Side Flash: Scripts, Databases, and Dynamic Development
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
mysql_select_db($flashbase,$hookup);
$numrows=mysql_num_rows($result);
$row=mysql_fetch_row($result);
$bof += $row[2];
$btc += $row[3];
$gcbb += $row[4];
page 329
Server-Side Flash: Scripts, Databases, and Dynamic Development
bofI=0,btcI=0,gcbbI=0",$hookup);
$inrow=mysql_fetch_row($result);
$newline=chr(13);
. $inrow[2];
$inventoryNow="inventory=$inven";
echo "$inventoryNow";
?>
The final PHP script (shown in Listing 11-7) marks the transaction as complete. In the cus_comp table,
a default N for “Not filled” is changed to a Y for “Yes, it’s filled.” The UPDATE query in this script, though,
is not global. It targets a single record identified by the unique customer ID. To target a particular record,
the UPDATE query includes a WHERE condition that is identified by the customer number entered in the
Flash input text field.
Listing 11-7: The complete.php Script
<?php
$user="domainNm_bill"; //Username
$pass="yourPassword"; //Password
mysql_select_db($flashbase,$hookup);
page 330
Server-Side Flash: Scripts, Databases, and Dynamic Development
echo "saleComplete=Completed";
?>
Figure 11-8: The order information shows how much the customer has spent on each of the services or
products.
page 331
Server-Side Flash: Scripts, Databases, and Dynamic Development
Figure 11-9: All of the customer contact information and inventory totals appear on the last frame of the
movie when the buttons are clicked.
When you have a secure credit card fund transfer, the amounts can be put into an accounting module
that is accessible only to the account administrator through a secure site. The user should never see the
movie developed in this chapter, only the one from Chapter 10. When you add an accounting module,
all of the purchases, returns, and payments can be recorded using a Flash 5 front end and PHP,
MySQL and an Apache server on the back end. If you prefer, you could translate the scripts in this
chapter into VBScript in order to create ASP pages that use an Access database to accomplish the
same goals as PHP and MySQL achieve in this chapter.
Summary
When thinking of an eBusiness site using Flash, you need to consider a front end for both the customer
and the business person who must administer the orders and payments for the site. By considering both
front ends in relationship to a back end written in PHP, ASP or Perl, you can simplify and streamline the
eBusiness process making it far more effective and efficient for both customer and owner. Perhaps the
most important lesson to learn besides the dual coordination of client and administrator modules is
using the data entered by the customer most effectively. When an order is placed for a product that
reduces an inventory, the data entered by the customer is the same data that will decrement the
inventory — you should not have to re-enter it on the administrative side of the equation. Mundane
calculations like adding tax and shipping should be automated so that the server or client script can use
client data to make all the necessary computations. More complex transactions require more complex
coding, but in the long run, the time you spend creating good customer and administrator pages and
sites pays off in effective and efficient order processing and customer satisfaction.
page 332
Server-Side Flash: Scripts, Databases, and Dynamic Development
System Requirements
Make sure that your computer meets the minimum system requirements listed in this section. If your
computer doesn’t match up to most of these requirements, you may have a problem using the contents
of the CD.
Windows
Macromedia recommends the following minimum requirements for running Flash 5 on a Windows
system:
Intel Pentium processor, 133 MHz or equivalent (200 recommended) processor
Windows 95/98, ME, Windows 2000, NT 4.0 or later
32MB of available RAM (64MB recommended)
40MB of available disk space
Color monitor capable of 800 x 600 resolution
CD-ROM drive
Macintosh
Macromedia recommends the following minimum requirements for running Flash 5 on a Macintosh:
Power Macintosh PowerPC (G3 or higher recommended)
MacOS 8.5 or later
32MB of available RAM
40MB of available disk space
Color monitor capable of 800 x 600 resolution
CD-ROM drive
Note These are the minimum requirements. As with all graphics-based design tools,
more capability is definitely better for using Flash 5, especially in terms of
memory and processor speed.
What’s on the CD
The CD-ROM contains scripts and FLA files for the examples used in the book, along with trial versions
of a number of applications. The following sections provide a summary of the contents of the CD-ROM,
arranged by category.
Source code
Every program file with a listing in the book is on the CD-ROM in a folder named after the chapter
associated with the file. Source code for Flash 5 files is designated with the FLA extension, and all
source files for Flash must be loaded into Flash 5. Files written for different server-side applications are
formatted and saved as text files. These files may be opened with any text editor, such as Notepad or
WordPad in Windows, or SimpleText on the Macintosh. Sometimes Notepad shows dark blocks where
carriage returns should go in the text files with the source code. Either remove the blocks or use another
text editor such as WordPad. The source code listings in the book show where carriage returns are
required in Notepad.
Applications
Trial, demo, or evaluation versions of programs are usually limited either by time or functionality, such
as not allowing you to save projects. The CD-ROM provides trial versions of the following programs:
Macromedia Fireworks (30-day trial version): Fireworks is a graphics-editing program
designed especially for Web applications.
page 333
Server-Side Flash: Scripts, Databases, and Dynamic Development
Installing PHP, Apache Server, and MySQL on your own hard drive is fairly simple. By following the
prompts, you shouldn’t encounter any problems with installation. Configuring your software so that it
runs reliably, however, depends on the version of the operating system you are using and the related
software on your system. Rather than providing configuration information for the various versions of
Windows, Linux, and Unix, we suggest that you start out by using PHP and MySQL on the free trial Web
hosting services provided on the CD. Your scripts and databases may work smoothly when you run
them on a remote host, but you may run into problems when you use your own system as both host and
server. The problems you’re likely to encounter depend to a great extent on the type of system you’re
running, and those variations are too lengthy to cover here. For help on configuring your system to act
as both client and server, pick up a book dedicated to the specific software you want to use.
If you want to take advantage of the Web hosting offers provided by JTLNet and HosTek, you can find
detailed instructions for accessing these services on the CD. The following steps, however, give you a
general idea of how this offer works:
To access JTLNet:
1. Click the JTLNet HTML file provided on the CD to go to the Web page for this special
trial hosting offer.
2. Complete the forms that request your name, e-mail address, and so on.
3. When you reach the section of the form requesting credit card information, a
message box appears to assure you that your credit card information is used solely
for verification purposes. No charges are billed to it during the 30-day free trial period.
4. When you have completed the required information on the forms, click Submit. You
receive an e-mail confirmation stating that your order will be processed within 24
hours, and then your username and password are sent to you via e-mail.
You don’t have to take any action to cancel the Web hosting service at the end of the 30-day free trial
period. You receive an e-mail stating this, and all your credit card information is discarded. This final e-
mail includes a link that you can click if you want to continue the hosting service for a fee.
To access HosTek:
1. To access the order page, point your browser to this address:
https://www.hostek.net/order.shtml
2. When you see the question “How Did You Hear About Us?” displayed near the top of
the page, click the option for Other and type HMSSF01 in the box.
3. Fill in the required information, including your credit card data, and click the Submit
Form/Read Contract button.
4. Read the Terms of Service and, if you agree to them, click the Accept button.
You must have a domain name to use the service. If you don’t have one, HosTek can register a domain
(.com/.net/.org) for you for $10 per year. Details about this process are provided in the Domain Name
section. This offer is good for NT servers only. Be sure to also choose a hosting plan, even if you use
the HosTek service for only the free 30-day trial period.
page 334
Server-Side Flash: Scripts, Databases, and Dynamic Development
Note: Your first 30 days are free. You can cancel the service any time before the 30th day and owe
absolutely nothing. If you continue past the 30th day, your credit card is charged according to the
hosting plan you selected. To cancel your trial account, send an e-mail to: [email protected], and
include your Customer ID and password.
Troubleshooting
If you have difficulty installing or using the CD-ROM, try the following solutions:
Turn off any antivirus software that you may have running. Installers sometimes mimic
virus activity and can make your computer incorrectly believe that it is being infected by a
virus. (Be sure to turn the antivirus software back on later.)
Close all running programs. The more programs you’re running, the less memory is
available to other programs. Installers also typically update files and programs; if you keep
other programs running, installation may not work properly.
Reference the ReadMe.txt. Please refer to the ReadMe file located at the root of the CD-
ROM for the latest product information at the time of publication.
If you still have trouble with the CD, please call the Hungry Minds Customer Service phone number:
(800) 762-2974. Outside the United States, call (317) 572-3993. You can also contact Hungry Minds
Customer Service by e-mail at [email protected]. Hungry Minds provides technical
support only for installation and other general quality control items; for technical support on the
applications themselves, consult the program’s vendor or author.
page 335