AS Reference  :  Notes Index  :  Resources  :  About/Contact  :  Downloads

LoadVars


The LoadVars class, introduced in Flash MX, allows sending of data between Flash and a web server, and provides a callback mechanism for dealing with data returned from the server (asynchronously).

Sending data to the server

The steps for sending data to a serverside script (PHP, ASP, Coldfusion, JSP, etc) are:

You have the choice of specifying GET (in which case the parameters you pass will be visible in the URL as an appended querystring) or POST for sending the data. Note that if you are testing from within the Flash IDE, eg for testing, you can only issue a GET -- POSTS only work when sent from Flash running in a browser.

Sending data to and receiving data from the server

To send and receive data (the more usual case, as it's good to know whether the operation succeeded or failed even if you don't want any other information from the server), the steps are:

An example of LoadVars sending data from Flash to PHP

If, for example, you wanted your Flash movie to get a username and password from a site visitor and forward them to another non-Flash page at the site with an appropriate message, you could use something like this Flash form:

which contains two TextInput components named username and password (valid combos, according to the PHP script, are Fred/0001, Jane/2000, or Mary/3333) and a Button component named enterbtn and has this code in frame 1:

// create an instance of LoadVars to send data
var dataOut:LoadVars = new LoadVars();

function checkUser():Void {
   dataOut.username = username.text;
   dataOut.password = password.text;
   dataOut.send("checkuser1.php", "newwin", "POST");
}

enterbtn.addEventListener("click", checkUser);

together with this PHP script, checkuser1.php (though the more likely scenario would be to do a database lookup instead):

checkuser1.php

<?
$users = array(
   'Fred' => '0001',
   'Jane' => '2000',
   'Mary' => '3333');

$d = getdate();
$found = false;

foreach($users as $un => $pw) {
   if ($_POST['username']==$un && $_POST['password']==$pw) {
      echo 'Welcome. The time here in Washington DC is '.$d['hours'].':'.$d['minutes'];
      $found = true;
      break;
   }
}

if (!$found) {
   echo 'Sorry, you are not cleared to know what time it is now in Washington DC';
}
?>
You can see if you try the Flash form above with a username and password from the list in the PHP script, a new window will be opened with a message telling you the time, whereas if you enter anything else, the new window will display a different message. If you want the window contents to display in the same window as the one the Flash movie is embedded in, use "_self" in place of "newwin" in the send method of LoadVars.

An example of LoadVars sending data from Flash to PHP and receiving data back

Data sent from a serverside script to Flash must be sent in a specific format if it is to be read within a LoadVars onLoad routine. It must consist of variable=value pairs separated by ampersands. It's also a good idea to put an ampersand at the beginning and end of the string being sent back, to make sure nothing extraneous is added to the variable name at the beginning of the string, or to the value at the end. If the example above were reworked to display the result within the Flash movie instead of in a separate browser window, the script could return two pieces of data: an indication of whether the username/password was found, and the current time. Thus, a legitimate return string could be

"&valid=1&time=14:30&

Here is the same movie with the result displayed in the Flash movie itself instead of another browser window:

It's the same content as above, plus a TextArea component named msg. This is the code in frame 1:

// hide the message box til there is something to display
msg.setStyle("backgroundColor", 0x003399);
msg.setStyle("borderStyle", "none");
msg.setStyle("color", 0xffffff);

// create two new instances of LoadVars, one to send and one to receive data
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();

// define what should happen when the response is received,
// using 'this' to refer to dataIn and get data from it
dataIn.onLoad = function() {
   if (this.valid=="1") {
      msg.text = 'Welcome. The time here in Washington DC is ' + this.time;
   } else {
      msg.text = 'Sorry, you are not cleared to know what time it is now in Washington DC';
   }
}

// the function that will be called by the Enter button 
function checkUser():Void {
   dataOut.username = username.text;
   dataOut.password = password.text;
   dataOut.sendAndLoad("checkuser2.php", dataIn, "POST");
}

// define the behavior of the Enter button
enterbtn.addEventListener("click", checkUser);

And this is the PHP script (checkuser2.php):

checkuser2.php

<?
$users = array(
      'Fred' => '0001',
      'Jane' => '2000',
      'Mary' => '3333');

$d = getdate();
$found = false;

foreach($users as $un => $pw) {
	if ($_POST['username']==$un && $_POST['password']==$pw) {
		echo '&valid=1&time='.$d['hours'].':'.$d['minutes'].'&';
		$found = true;
		break;
	}
}

if (!$found) echo '&valid=0&';
?>

Notice that the only difference between checkuser2.php and checkuser1.php above is the echo string. In checkuser1.php, where the output is destined for the browser window, the echoed string is formatted for display. In checkuser2.php, where the output is destined for Flash, the echo string is made up of variable=value pairs, surrounded by &s. Flash itself will format this returned data for display, within the LoadVars onLoad routine.

Intro
Flash: What & How
Example Sites
Create
Draw, Edit Shapes
Gradients
More Drawing Tips
Import
A Sample
Animate
Frames, Keyframes
Motion Tweens
More Motion Tweens
Shape Tweens
Masks
Control
Stop/Replay
Movieclips Intro
Movieclip Reference
Site Structure 1
Slideshow Movieclip
Contact Form
Scroll Resume
Preloader
Site Structure 2
Publish
Display Options
Player Detection
Optimize
AS 2.0 Basics
Intro to Syntax
Playhead Commands
Playhead Cmds 2
Coded Tween
onEnterFrame
Intro to Classes
Declare/Assign
Comments, Trace
Simple Data Types
Arrays & Objects
Code Blocks
Operators
Beyond Buttons
Code Structure
Toggle Controls
Group of Buttons
Drag and Hit
Distort Magnifier
Scroll Text
Bee Game
Dart Shooter
Sound Control
Easing Slider
Easing Slider 2
Components Intro
Timers & Delays
Dynamic Content
Intro
Drawing API
Create Text
Attach Movieclips
Easing Slider 3
Easing Slider 4
Load jpg/swf
Sliding Viewer
Preload swf
XML
Easing Slider 5
Server Comm
LoadVars (w/ PHP)
AS - PHP Lookup
Text File
Database 1:LoadVars
Database 2:Remoting
Read from directory
AS 2.0 Classes
Intro
Math
Key
Date
Color
EventDispatcher
New Samples
Pie Chart
Event-model Emailer
Tween Sequence
Fuse Sequence
SVG in Flash
Bitmap Topo
SWF as Data Holder
Two-level Menu
Yahoo! Flash Maps
Class-based Game
ASTB Samples
Disclaimer
3D Outlines
Bounce Collide
Address Book
Save Drawings
Home  :  Notes Index  :  Resources  :  About/Contact  :  Downloads