nunomira.com nunomira.com   tutorials
   
   

Loading Variables

There are many reasons why you may want to load data into flash from an external source, and there are also many different sources where the data can come from.
Updating an external source is much easier than updating a swf. The simplest of all the sources is a text file. In a complex application you may need a database (such as MySQL) and a server side script (such as PHP or ColdFusion).

Prior to flash MX, there were only two functions (or methods) to load data into flash:
loadVariables() and loadVariablesNum().

The LoadVars() class introduced in flash MX has made everything more straightforward and easier.

Topics


The data in the text file

There are some basic rules to store the data in the text file:

  • The variables have to be URL-encoded;
  • The variable name/value pair is separated by an equals (=) sign, without spaces, as in fName=nuno or age=24;
    If you want to make sure that there are no extra spaces at all, surround everything with ampersands (&), as in &fName=nuno&;
  • If you have more than one variable you separate them with an ampersand (&), as in fName=nuno&lName=mira&age=24 or &fName=nuno&lName=mira&age=24&.
    Ampersands are also useful to avoid having to write everything in a row, i.e., without pressing the Enter key:
    while
    fName=nuno&lName=mira&age=24
    isn't easy to read, and
    fname=nuno
    lname=mira
    age=24

    isn't valid,
    &fname=nuno&
    &lname=mira&
    &age=24&

    is both valid and easy to read.
  • In notepad, if you're using some characters like à or é, you have to save the text file as UTF-8.

loadVariables() and loadVariablesNum()

If you're using MX, I can't see why you would use loadVariables() or loadVariablesNum()... anyway...

loadVariables(url, target, method)
mc.loadVariables(url, method)
loadVariablesNum(url, level, method)

  • url - a string with the url to the external source such as external.txt or myVariables.php;
  • target, mc - the target path to a movie clip where the variables will be sent to;
  • method - optional parameter; either GET or POST;
    if used, variables are sent and received, if omitted, variables are only sent.
  • level - the target is not a movie clip but a level, such as _level0, _level1... i.e., _levelN.


Suppose you have the following code attached to the main timeline:
some_mc.loadVariables("external.txt");
where some_mc is a movie clip on the stage
and in the text file external.txt you have:
&fName=nuno&
&
lName=mira&
&age=24&

after the variables finish loading, they can be called like this:
trace(some_mc.fName); // outputs nuno
trace(some_mc.age); // outputs 24

download .fla: 1

Notice that every variable that has been loaded is a string:
trace(typeof(some_mc.fName)); // string
Even some_mc.age, which you might think was a number, is a string:
trace(typeof(some_mc.age)); // string
but can be easily converted to a number:
some_mc.age = Number(some_mc.age);

download .fla: 2

In the same way, if you use loadVariablesNum():
loadVariablesNum("external.txt", 7);
and want to call the variables:
trace(_level7.fName); // nuno

download .fla: 3

loadVariables() and loadVariablesNum() are quite similar, so, from now on, I'll just mention loadVariables(), but will have loadVariablesNum()in mind as well.

When you load variables from a text file, it doesn't make sense specifying the method parameter - GET or POST - because it doesn't make any sense sending variables to a text file either.

The main difficulty in loading data is making sure that the information you have loaded is already available when you want to use it, that's why using onLoad() with the LoadVars() class is so wonderful!

Preloading variables

In the text file you can use an extra variable, e.g.: done=yes. If the variable done equals the string yes, it means that all the variables are available.

Code in external.txt:
&fName=nuno&lName=mira&age=24&done=yes&
Code in flash:
some_mc.loadVariables("external.txt");
// create a loop
some_mc.onEnterFrame = function(){
  //the variables have finished loading
  if(this.done == "yes"){
    //do something...
    //delete the method to end the loop
    delete this.onEnterFrame;
  }
};

There is no point in using done=true because, like said before, when done is loaded, it is a string, not a boolean, so, to test it, you would have to use
if(done == "true"){
  //loaded
}

, not
if(done == true){
  // loaded
}


LoadVars()

These are some of the methods:
load(url)
send(url, target, method)
sendAndLoad(url, targetObject, method)
onLoad()

  • target - optional parameter; in this context, is the name of the browser window or frame; or the usual "_blank", "_self", ...
  • targetObject - the object created with new LoadVars() that will receive the data

Using LoadVars() saves you the trouble of having to preload the variables.

This is how you use loadVars() instead of loadVariables() :

// create an object to store the variables
varReceiver = new LoadVars();
// load the variables from the text file
varReceiver.load("external.txt");
// trigger something - when the variables finish loading
varReceiver.onLoad = function(){
  //the variables have finished loading
  //do something...
  trace(this.fName); // you use the this keyword to call the variables stored in the object varReceiver
  trace(this.age);
};

download .fla: 4

PHP

To send variables from a php script, you have either to echo() or print() the variables. Apart from this, it is exactly the same as using a text file:

<?php
$fName = "nuno";
$lname = "mira";
$age = 24;
// echo or print the variables
echo ("&fName=$fName&lName=$lName&age=$age&");
?>

download .fla: 5

Like before, if you're using characters like á or é, you have to use utf8_encode():
<?php
$myVar = "olá";
$myVar = utf8_encode ($myVar);
print ("&myVar=$myVar&"); // using print(), for a change
?>

download .fla: 6

This is for illustrative purpose only because in this case using a .php file or a .txt file is the same.
If you are using loadVariables(), you can use the extra variable done:
<?php
$fName = "nuno";
$lname = "mira";
$age = 24;
$done = "yes";
echo ("&fName=$fName&lName=$lName&age=$age&done=$done&");
?>

Until now we have only loaded variables into flash (the method parameter GET or POST have never been used). Now we are going to send variables from flash, and, depending on what we send, we're going to receive different values.

Suppose a user chooses to buy a cd and there are two editions - normal and special - and the special edition is more expensive.
All the details of the of the user's choice are stored in the object varSender:

// create the object to store the user's choices
varSender = new LoadVars();
// create the object to receive the cd's price
varReceiver = new LoadVars();
// the user choses a cd called some_cd
varSender.cd = "some_cd";
// and the special edition
varSender.edition = "special";
// send the details of the choice to the php script
// and get the price
varSender.sendAndLoad("price.php", varReceiver, "POST"); // specifying a method is required
  varReceiver.onLoad = function(){
  trace(this.price); // outputs 17
};

And in price.php:

<?php
$cd = $_POST['cd'];
$edition = $_POST['edition'];
if ($cd == "some_cd"){
  if ($edition == "normal"){
    $price = 15;
  } else if ($edition == "special"){
    $price = 17;
  }
} else if ($cd == "other_cd"){
  // other options...
}
echo ("&price=$price&");
?>

download .fla: 7

Once again, this is just a simple example... If this was a complex application, information like this would come from a database, it wouldn't be written on a file.


HTML tags

Another way of sending variables to flash is through the html tags that embed the swf. This can be done in two ways - using FlashVars or using a query string.

This is the html that embeds a flash movie called example.swf, created by flash, when you publish the file:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,79,0" width="550" height="400">
<param name="movie" value="example.swf" />
<param name="quality" value="high" />
<embed src="example.swf" width="550" height="400" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>
</object>

The same code using FlashVars:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,79,0" width="550" height="400">
<param name="movie" value="example.swf" />
<param name="quality" value="high" />
<param name="FLashVars" value="myName=nuno%20mira&amp;age=24" />
<embed src="example.swf" width="550" height="400" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" flashvars="myName=nuno%20mira&amp;age=24"></embed>
</object>

download .fla: 8

The same code using a query string:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,79,0" width="550" height="400">
<param name="movie" value="example.swf?age=24&amp;myName=nuno%20mira" />
<param name="quality" value="high" />
<embed src="example.swf?age=24&myName=nuno%20mira" width="550" height="400" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>
</object>

download .fla: 9

In both examples, the two variables - age = 24 and myName = nuno mira - are sent to the flash movie.
These variables are available at _level0 and can be called like this:
trace(_level0.age); // outputs 24
trace(_level0.myName); // outputs nuno mira

Both ways are easily achieved in Dreamweaver, either hard-coding or using javascript or a server side script like php.
For instance, my web site uses php to get the variable lang - en or pt - from the url and send the chosen value to flash.
The url can be http://www.nunomira.com/flash.php?lang=en or http://www.nunomira.com/flash.php?lang=en depending on the links the user clicks.

view image from DW's property panel
view image from DW's property panel
view image from DW's property panel

get the variable from the url:
<?php
$lang = $_GET['lang'];
?>
send it to flash:
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,79,0" width="751" height="451">
<param name="movie" value="nunomira.swf<?php echo "?lang=$lang"; ?>" />
<param name="quality" value="high" />
<embed src="nunomira.swf<?php echo "?lang=$lang"; ?>" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="751" height="451"></embed></object>

download .fla: 10

Related topics

Loading an array from a text file
You can't load an array directly from a text file, but you can use a simple trick: using a different character to separate what will be the elements of the array, and split(). For example, if you want to obtain the following array in flash:
myArray = ["php", "mysql", "actionscript", "html"]
in the text file you write something like:
&myArray=php|mysql|actionscript|html&
i.e., (|) will be the separating character,
and in flash:
varReceiver = new LoadVars();
varReceiver.load("external.txt");
varReceiver.onLoad = function(){
  trace(typeof (this.myArray)); // string
  this.myArray = this.myArray.split("|");
  trace(typeof (this.myArray)); // object
  trace(this.myArray.length); // 4

};

download .fla: 11

Prevent data from caching
To achieve this, you use a simple trick known as a cache killer: appending a unique value as a query string to the url of the file you're loading. Actually this works with any file: jpg, swf...
// generate a unique value
var cKiller = new Date().getTime();
// append it to the url of the file:
varReceiver.load("external.txt?cKiller=" + cKiller); // text file
some_mc.loadVariables("external.txt?cKiller=" + cKiller); // text file
some_mc.loadMovie("external.swf?cKiller=" + cKiller); // flash movie
This works only on a web server. If you test it locally without one, you'll get an error.

Links

   
   
nunomira.com nunomira.com   tutorials