Note: This article is the first in a series which describes how to connect a Flash project with a database, or more generally, how to pull external data into a .swf file playing in the Flash Player. The series introduction contains a list of all the articles.
If you’d like, you can: Download the example files Skip to the summary at the end
Review: How a Flash Player movie (.swf file) is “embedded” into a web page.
Because the HTML source code that activates the Flash Player is so important to this approach, I will take a moment to review what it looks like and how it works. If you feel comfortable with this topic already, feel free to skip down to the next section.
In general, to embed a .swf file in a web page two HTML tags are used. You can see this by creating a new Flash project and choosing File > Publish to create a .swf file and a basic HTML page container (the default Publish Settings are to create both a .swf file and a web page). Once you have published the movie, you can view the source code for the container web page. Using the standard templatenote 1 that comes with Flash MX 2004, the portion of the code that specifies to include the .swf file will look something like this:
. . . <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="550" height="400" id="URLvariables" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="URLvariables.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="URLvariables.swf" quality="high" bgcolor="#ffffff" width="550" height="400" name="URLvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> . . .
As mentioned, there are two tags, the <object> tag (and it’s child <param> tags) which are used by Internet Explorer (Windows), and the <embed> tag which is used by all other browsersnote 2. You can see that each of these tags specify several values that control the behavior of the Flash Player, such as the URL of the .swf file, the background color, the playback quality, etc. In general, these correspond to options that are selected in the Publish Settings… dialog box. The most important thing to note is that, since there are actually two separate tags which perform the job of activating the Flash Player, each value appears twice, usually in a <param> tag for the options associated with the <object> tag and as attributes within the <embed> tag.
URL Variable Format
If you have done any dynamic web page programming or have paid some attention to the way web browsers work, you have probably noticed that in some cases, for example when you submit the search form on Google, certain variable values are passed to the web server as part the URL. The variables appear at the end of the URL, like this: http://www.example.com/index.php?var1=value1&var2=value2
A question mark designates the beginning of the variables. Next each variable and its value appear as a pair with an equals sign. Variable/value pairs are separated by the ampersand (&) character. This format is often referred to as URL variable format or querystring format. In this format most characters other than regular latin alphabet characters must be encoded in a special format (known as “URL encoding”) in order for them to be passed correctly. Most web programming systems include some command for doing this (e.g. Server.UrlEncode() in ASP/ASP.NET; urlencode() in PHP).
Passing values to the .swf file
Just as URL variables can be appended to a URL to pass values to a web page on a server, they can be used in just the same way to pass values into a .swf file in the Flash Player. When you add a URL variable sequence to the end of the .swf filename which is passed to the Flash Player (in the “movie” <param> tag or in the <embed> tag’s “src” attribute), variables with the specified names will be created and assigned the specified values. Those variables will be created on the main timeline of the Flash project, and will be available to any ActionScript on that timeline (or using _root.variableName).
For example, the sample file URLVariables.fla has a single dynamic text field on the stage, with an instance name of myTextField_txt. There is a single line of ActionScript on the first frame which reads:
myTextField_txt.text = var1;
In the source code for the companion HTML file, URLVariables.html, a URL variable sequence has been added to the end of the .swf file’s name with a single variable named “var1”, which is given the text value “value1”. The important lines of code look like this:
... <param name="movie" value="URLvariables.swf?var1=value" /> ... <embed src="URLvariables.swf?var1=value" quality="high" bgcolor="#ffffff" width="550" height="400" name="URLvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> ...
If you open this file in a browser, you will see the text “value1” in the text field, because the variable “var1” is created in the Flash project before the line of ActionScript is executed.
If you test this Flash project within Flash, you will see the text “undefined” in the text field, since the code assigns the value of the variable var1 (which has no value if the .swf file isn’t playing in a browser, hence “undefined”) to the text property of the text field.
Things to keep in mind
- You can specify multiple variables, and they will all be available to the Flash project.
- The values which are passed in are always text values, so the variables should be treated as String variablesnote 3.
- The values are only loaded into the movie once, when the movie first loads. There is no way to “re-query” those variables to get a different value, assuming it might have changed during the time the person is viewing the Flash movie.
Obviously there isn’t much utility in having the variables/values hard-coded in a static HTML page. To make this approach useful, you would use some sort of dynamic web page language to come up with some dynamic data, whether it is pulled out of a database, passed in through a form, etc. You would then code the page so that value given to the variable is dynamically written into the HTML source before returning it to the user – just as you would dynamically write any other content to the page. A working example of this is available in the example files as URLVariablesDynamic.fla, with its accompanying .swf file. You can try out a live demo of this project, and the PHP (and equivalent ASP.NET) files are also included in the example files.
However, for testing purposes it is common (and useful) to just use a static HTML page with the values hard-codednote 4. That way you can test your Flash project and get it working as desired first, then move on to coding the dynamic page portion. By testing the page with static data you can isolate any errors that happen during testing as being due to an error in the Flash project (and conversely, if things do work you will know that they should still be working when you hook it up with dynamic data).
One big limitation applies to this way of passing data into Flash. Normally, web browsers cache .swf files and will not generally download a new version of the .swf file. However, when you append URL variables to the .swf file’s URL, the general behavior is that web browsers will download a new copy of the .swf file, even if the .swf file itself hasn’t changed and only the text of the URL variable string has changed.
In most cases this is bad, because it means that users will be forced to re-download the same .swf file every time a variable’s value changes (even if nothing has changed in the .swf file itself). It can actually be beneficial if you want to force users to download a newer version of a .swf file (normally browsers won’t download the newer version even if the .swf file has changed). By appending a URL variable such as a version number, and changing that value in the HTML code every time you change the .swf file, you can make it much more likely that users will always see the current version of the .swf file. As long as the version number hasn’t changed, the user’s browser will generally use the copy in the cache, saving download time on return visits.
The next iteration: FlashVars
Macromedia recognized that the URL variables approach to loading data really isn’t acceptable, since it prevents browsers from using the cached copy of a .swf file. Consequently, with the release of Flash MX and the Flash Player version 6, they added support for a new construct known as FlashVars which can be used to accomplish the same task of passing in variables when a .swf file loads, but without the unwanted side effect of forcing the browser to download the .swf file again.
FlashVars works in a very similar way to the URL variables method of passing data into the Flash project. However, instead of appending the variables and values directly to the .swf filename, they are included as a separate parameter of the <object> and <embed> tags. To pass variables in using the FlashVars approach, add an extra <param> tag and an extra attribute to the <embed> tag. For the <param> tag the “name” attribute should be “flashvars” and the value should be the list of variable-and-value pairs, still in URL variable format (i.e. separated by ampersands, URL encoded, etc.). The <embed> tag’s new attribute is named “flashvars” and has the variable/value pairs as its value, in the same format.
Here is the same HTML code that we looked at before, modified to use FlashVars instead of URL variables:
. . . <param name="movie" value="URLvariables.swf" /> <param name="flashvars" value="var1=value" /> . . . <embed src="URLvariables.swf" flashvars="var1=value" quality="high" bgcolor="#ffffff" width="550" height="400" name="URLvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> . . .
You can see this code in context in the sample file FlashVars.html. Other than not forcing the browser to reload the .swf file, this approach works just the same from the Flash/ActionScript perspective (in fact, the example file uses the same .swf).
Complex/Large amounts of data
Admittedly, all the examples I’ve shown have been pretty simple overall. In general this approach isn’t the best to use if you want to bring in a large amount of data or data that is fairly complex. However, I will talk about one way that I have used to do this.
Suppose you want to create a Flash project that will be a generic graphing tool – you will feed it a set of labels and values, and it will create a bar chart of that data. The trick, of course, is that you don’t know exactly how many items will be passed in. Ultimately we will want the data to be in the Flash movie as multiple arrays, perhaps one which contains the values for the chart, and one which contains the labels associated with those values. One way to pass in one or more “arrays” of data using FlashVars is to have a variable representing each array you want to pass in, and then have the value assigned to that variable be a comma-separated list of values (or some other character that you know won’t be found in the data itself).
So for our charting example, we could have two variables, one named “labels” and one named “values”. The “value” of our FlashVars <param> tag/attribute in the HTML document would look something like this:
So when our movie loads, there would be two variables available to us, one named labelstring and one named valuestring. According to the Flash Player these would be String variables, so we would need to create our own Array objects out of those variables. That is easy enough to do using the split() method of the String class. To create our arrays, we would use these lines of ActionScript:
var labels:Array = labelstring.split(",");
var values:Array = valuestring.split(",");
We could then use those array variables to populate our chart or for whatever purpose we wanted to use them.
Here is a review of what we’ve covered in this article.
How to get the data into Flash:
- Choose the approach to use:
- URL Variables: append variables and values to the .swf file name in the HTML source code of the page (this usually means they have to be added in two places). The variables should be in a “URL Variable” format, like “mymovie.swf?var1=value1&var2=value2”.
- FlashVars: add an extra <param> tag and an extra attribute to the <embed> tag. The <param> tag’s name should be “flashvars” and value should be the list of variable and value pairs in URL variable format (no question mark is needed in this case). The <embed> attribute should be named “flashvars” and its value should be the list of variables in the specified format.
- In either case, when the .swf file loads in the Flash Player, the specified variables will be available as variables on the main timeline, with the given values.
- Easy to create.
- Easy to simulate passing in data, even without access to a web server.
- Doesn’t require additional (separate) server code aside from the page containing the .swf file.
- Simple to create a reusable widget (e.g. a graph) by reusing the same page with different data.
- Can’t test project in the standalone Flash Player which is built into Flash – must publish an html file.
- Can only pass values in when the movie is first loaded.
- No way to pass data out of the Flash movie.
- Creates a dependency between the .swf file and the html page which contains it – which goes against the general principle of designing “black box” elements that are self-contained or can be repurposed in different ways.
- Forces the .swf file to download (when using URL variables).
- Requires Flash Player version 5 (URL variables) or 6 (FlashVars).
- These two approaches aren’t in the official documentation, so they could (theoretically) be removed from future players without notice (although from a practical standpoint this is very unlikely). Update: they aren’t mentioned in the official documentation, but they are documented in this TechNote from Macromedia.
Note 1: There are several web page templates that are included with Flash. You can choose the one you want to use in the File > Publish Settings… dialog box. Under the HTML tab the Template pull-down menu can be used choose from several HTML page templates, depending on whether you need certain features in your Flash project. You can also create your own templates or customize the ones that come with Flash, as described in Flash Help > Using Flash > Publishing > About HTML publishing templates and the topics under Customizing HTML publishing templates.
Note 3: If you are like me and are a stickler about always declaring variables in your Flash projects, you can still declare them (as String variables). Since the Flash Player just ignores variable declaration statements for variables that are already defined, it won’t overwrite the value that was passed in the URL.
Note 4: Once you have published the movie the first time to create the HTML page, and edited the HTML source code to include the variables, be sure that you do not publish the Flash movie again without un-checking the option to publish an HTML file. If you publish a new HTML file, the file with the variables added in will be overwritten and the variables will be lost. This is only an issue if you “compile” the Flash project using File > Publish or File > Publish Preview; if you test the movie to create a new .swf file a new HTML page will not be generated.