Top Level

Class LoadVars

Object


public dynamic class LoadVars
extends Object

Player version: Flash Player 6

You can use the LoadVars class to obtain verification of successful data loading and to monitor download progress. The LoadVars class is an alternative to the loadVariables() function for transferring variables between a Flash application and a server.

The LoadVars class lets you send all the variables in an object to a specified URL and to load all the variables at a specified URL into an object. It also lets you send specific variables, rather than all variables, which can make your application more efficient. You can use the LoadVars.onLoad handler to ensure that your application runs when data is loaded, and not before.

The LoadVars class works much like the XML class; it uses the load(), send(), and sendAndLoad() methods to communicate with a server. The main difference between the LoadVars class and the XML class is that LoadVars transfers ActionScript name and value pairs, rather than an XML Document Object Model (DOM) tree stored in the XML object. The LoadVars class follows the same security restrictions as the XML class.

See also
loadVariables(), LoadVars.onLoad, XML



Property Summary
contentType : String
The MIME type that is sent to the server when you call LoadVars.send() or LoadVars.sendAndLoad().
loaded : Boolean
A Boolean value that indicates whether a load or sendAndLoad operation has completed, undefined by default.

Properties inherited from class Object
__proto__, __resolve, constructor, prototype


Event Summary
onData = function(src:String) {}
Invoked when data has completely downloaded from the server or when an error occurs while data is downloading from a server.
onHTTPStatus = function(httpStatus:Number) {}
Invoked when Flash Player receives an HTTP status code from the server.
onLoad = function(success:Boolean) {}
Invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has ended.


Constructor Summary
LoadVars()
Creates a LoadVars object.


Method Summary
addRequestHeader(header:Object, headerValue:String) : Void
Adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions.
decode(queryString:String) : Void
Converts the variable string to properties of the specified LoadVars object.
getBytesLoaded() : Number
Returns the number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad().
getBytesTotal() : Number
Returns the total number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad().
load(url:String) : Boolean
Downloads variables from the specified URL, parses the variable data, and places the resulting variables in my_lv.
send(url:String, target:String, [method:String]) : Boolean
Sends the variables in the my_lv object to the specified URL.
sendAndLoad(url:String, target:Object, [method:String]) : Boolean
Posts variables in the my_lv object to the specified URL.
toString() : String
Returns a string containing all enumerable variables in my_lv, in the MIME content encoding application/x-www-form-urlencoded.

Methods inherited from class Object
addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch


Property Detail

contentType Property

public contentType : String

Player version: Flash Player 6

The MIME type that is sent to the server when you call LoadVars.send() or LoadVars.sendAndLoad(). The default is application/x-www-form-urlencoded.

Example
The following example creates a LoadVars object and displays the default content type of the data that is sent to the server.
var my_lv:LoadVars = new LoadVars();
trace(my_lv.contentType);  // output: application/x-www-form-urlencoded

See also
LoadVars.send(), LoadVars.sendAndLoad()

loaded Property

public loaded : Boolean

Player version: Flash Player 6

A Boolean value that indicates whether a load or sendAndLoad operation has completed, undefined by default. When a LoadVars.load() or LoadVars.sendAndLoad() operation is started, the loaded property is set to false; when the operation completes, the loaded property is set to true. If the operation has not completed or has failed with an error, the loaded property remains set to false.

This property is similar to the XML.loadedproperty.

Example
The following example loads a text file and displays information in the Output panel when the operation completes.The following example loads a text file and writes information to the log file when the operation completes.
var my_lv:LoadVars = new LoadVars();
my_lv.onLoad = function(success:Boolean) {
    trace("LoadVars loaded successfully: "+this.loaded);
};
my_lv.load("http://www.helpexamples.com/flash/params.txt");

See also
LoadVars.load(), LoadVars.sendAndLoad(), XML.load()


Event Detail

onData Event Handler

public onData = function(src:String) {}

Player version: Flash Player 6

Invoked when data has completely downloaded from the server or when an error occurs while data is downloading from a server. This handler is invoked before the data is parsed and can be used to call a custom parsing routine instead of the one built in to Flash Player. The value of the src parameter passed to the function assigned to LoadVars.onData can be either undefined or a string that contains the URL-encoded name-value pairs downloaded from the server. If the src parameter is undefined, an error occurred while downloading the data from the server.

The default implementation of LoadVars.onData invokes LoadVars.onLoad. You can override this default implementation by assigning a custom function to LoadVars.onData, but LoadVars.onLoad is not called unless you call it in your implementation of LoadVars.onData.

Parameters
src:String — A string or undefined; the raw (unparsed) data from a LoadVars.load() or LoadVars.sendAndLoad() method call.

Example
The following example loads a text file and displays content in a TextArea instance called content_ta when the operation completes. If an error occurs, then information displays in the Output panel.If an error occurs, then information writes to the log file.
var my_lv:LoadVars = new LoadVars();
my_lv.onData = function(src:String) {
    if (src == undefined) {
        trace("Error loading content.");
        return;
    }
    content_ta.text = src;
};
my_lv.load("content.txt", my_lv, "GET");

See also
LoadVars.onLoad, LoadVars.onLoad, LoadVars.load(), LoadVars.sendAndLoad()

onHTTPStatus Event Handler

public onHTTPStatus = function(httpStatus:Number) {}

Player version: Flash Player 8

Invoked when Flash Player receives an HTTP status code from the server. This handler lets you capture and act on HTTP status codes.

The onHTTPStatus handler is invoked before onData, which triggers calls to onLoad with a value of undefined if the load fails. After onHTTPStatus is triggered, onData is always triggered, whether or not you override onHTTPStatus. To best use the onHTTPStatus handler, you should write a function to catch the result of the onHTTPStatus call; you can then use the result in your onData and onLoad handlers. If onHTTPStatus is not invoked, this indicates that the player did not try to make the URL request. This can happen because the request violates security sandbox rules for the SWF file.

If Flash Player cannot get a status code from the server, or if it cannot communicate with the server, the default value of 0 is passed to your ActionScript code. A value of 0 can be generated in any player (for example, if a malformed URL is requested), and a value of 0 is always generated by the Flash Player plug-in when it is run in the following browsers, which do not pass HTTP status codes to the player: Netscape, Mozilla, Safari, Opera, and Internet Explorer for the Macintosh.

Parameters
httpStatus:Number — The HTTP status code returned by the server. For example, a value of 404 indicates that the server has not found a match for the requested URI. HTTP status codes can be found in sections 10.4 and 10.5 of the HTTP specification at ftp://ftp.isi.edu/in-notes/rfc2616.txt.

Example
The following example shows how to use onHTTPStatus() to help with debugging. The example collects HTTP status codes and assigns their value and type to an instance of the LoadVars object. (Notice that this example creates the instance members this.httpStatus and this.httpStatusType at runtime.) The onData method uses these instance members to trace information about the HTTP response that can be useful in debugging.
var myLoadVars:LoadVars = new LoadVars();

myLoadVars.onHTTPStatus = function(httpStatus:Number) {
    this.httpStatus = httpStatus;
    if(httpStatus < 100) {
        this.httpStatusType = "flashError";
    }
    else if(httpStatus < 200) {
        this.httpStatusType = "informational";
    }
    else if(httpStatus < 300) {
        this.httpStatusType = "successful";
    }
    else if(httpStatus < 400) {
        this.httpStatusType = "redirection";
    }
    else if(httpStatus < 500) {
        this.httpStatusType = "clientError";
    }
    else if(httpStatus < 600) {
        this.httpStatusType = "serverError";
    }
}

myLoadVars.onData = function(src:String) {
    trace(">> " + this.httpStatusType + ": " + this.httpStatus);
    if(src != undefined) {
        this.decode(src);
        this.loaded = true;
        this.onLoad(true);
    }
    else {
        this.onLoad(false);
    }
}

myLoadVars.onLoad = function(success:Boolean) {
}
    
myLoadVars.load("http://weblogs.macromedia.com/mxna/flashservices/getMostRecentPosts.cfm");

See also
XML.onHTTPStatus, LoadVars.load(), LoadVars.sendAndLoad()

onLoad Event Handler

public onLoad = function(success:Boolean) {}

Player version: Flash Player 6

Invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has ended. If the operation was successful, my_lv is populated with variables downloaded by the operation, and these variables are available when this handler is invoked.

This handler is undefined by default.

This event handler is similar to XML.onLoad.

Parameters
success:Boolean — A Boolean value that indicates whether the load operation ended in success (true) or failure (false).

Example
The following example adds a TextInput instance called name_ti, a TextArea instance called result_ta, and a Button instance called submit_button to the Stage. When the user clicks the Login button instance, two LoadVars objects are created: send_lv and result_lv. The send_lv object copies the name from the name_ti instance and sends the data to greeting.cfm. The result from this script loads into the result_lv object, and the server response is displayed in the TextArea instance (result_ta). Add the following ActionScript on Frame 1 of the Timeline:
var submitListener:Object = new Object();
submitListener.click = function(evt:Object) {
    var result_lv:LoadVars = new LoadVars();
    result_lv.onLoad = function(success:Boolean) {
        if (success) {
            result_ta.text = result_lv.welcomeMessage;
        } else {
            result_ta.text = "Error connecting to server.";
        }
    };
    var send_lv:LoadVars = new LoadVars();
    send_lv.name = name_ti.text;
    send_lv.sendAndLoad("http://www.flash-mx.com/mm/greeting.cfm", result_lv, "POST");
};
submit_button.addEventListener("click", submitListener);
To view a more robust example, see the login.fla file in the ActionScript samples folder. Here are some typical paths to this folder:

See also
XML.onLoad, LoadVars.loaded, LoadVars.load(), LoadVars.sendAndLoad()


Constructor Detail

LoadVars Constructor

public LoadVars()

Player version: Flash Player 6

Creates a LoadVars object. You can then use the methods of that LoadVars object to send and load data.

Example
The following example creates a LoadVars object called my_lv:
var my_lv:LoadVars = new LoadVars();



Method Detail

addRequestHeader Method

public addRequestHeader(header:Object, headerValue:String) : Void

Player version: Flash Player 6

Adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings to the method: header and headerValue. In the second usage, you pass an array of strings, alternating header names and header values.

If multiple calls are made to set the same header name, each successive value will replace the value set in the previous call.

The following standard HTTP headers cannot be added or changed with this method: Accept-Ranges, Age, Allow, Allowed, Connection, Content-Length, Content-Location, Content-Range, ETag, Host, Last-Modified, Locations, Max-Forwards, Proxy-Authenticate, Proxy-Authorization, Public, Range, Retry-After, Server, TE, Trailer, Transfer-Encoding, Upgrade, URI, Vary, Via, Warning, and WWW-Authenticate.

Parameters
header:Object — A string or array of strings that represents an HTTP request header name.
headerValue:String — A string that represents the value associated with header.

Example
The following example adds a custom HTTP header named SOAPAction with a value of Foo to the my_lv object:
my_lv.addRequestHeader("SOAPAction", "'Foo'");

The following example creates an array named headers that contains two alternating HTTP headers and their associated values. The array is passed as an argument to addRequestHeader().

var headers = ["Content-Type", "text/plain", "X-ClientAppVersion", "2.0"];
my_lv.addRequestHeader(headers);

The following example creates a new LoadVars object that adds a request header called FLASH-UUID. The header contains a variable that can be checked by the server.

var my_lv:LoadVars = new LoadVars();
my_lv.addRequestHeader("FLASH-UUID", "41472");
my_lv.name = "Mort";
my_lv.age = 26;
my_lv.send("http://flash-mx.com/mm/cgivars.cfm", "_blank", "POST");

See also
XML.addRequestHeader()

decode Method

public decode(queryString:String) : Void

Player version: Flash Player 7

Converts the variable string to properties of the specified LoadVars object.

This method is used internally by the LoadVars.onData event handler. Most users do not need to call this method directly. If you override the LoadVars.onData event handler, you can explicitly call LoadVars.decode() to parse a string of variables.

Parameters
queryString:String — A URL-encoded query string containing name/value pairs.

Example
The following example traces the three variables:
// Create a new LoadVars object
var my_lv:LoadVars = new LoadVars();
//Convert the variable string to properties
my_lv.decode("name=Mort&score=250000");
trace(my_lv.toString());
// Iterate over properties in my_lv
for (var prop in my_lv) {
    trace(prop+" -> "+my_lv[prop]);
}

See also
LoadVars.onData, XML.parseXML()

getBytesLoaded Method

public getBytesLoaded() : Number

Player version: Flash Player 6

Returns the number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad(). This method returns undefined if no load operation is in progress or if a load operation has not yet begun.

Returns
Number — An integer.

Example
The following example uses a ProgressBar instance and a LoadVars object to download a text file. When you test the file, two things are displayed in the Output panel:When you test the file, two things write to the log file: whether the file loads successfully and how much data loads into the SWF file. You must replace the URL parameter of the LoadVars.load() command so that the parameter refers to a valid text file using HTTP. If you attempt to use this example to load a local file that resides on your hard disk, this example will not work properly because in Test Movie modetest mode Flash Player loads local files in their entirety. To see this code work, add a ProgressBar instance called loadvars_pb to the Stage. Then add the following ActionScript to Frame 1 of the Timeline:
var loadvars_pb:mx.controls.ProgressBar;
var my_lv:LoadVars = new LoadVars();
loadvars_pb.mode = "manual";
this.createEmptyMovieClip("timer_mc", 999);
timer_mc.onEnterFrame = function() {
    var lvBytesLoaded:Number = my_lv.getBytesLoaded();
    var lvBytesTotal:Number = my_lv.getBytesTotal();
    if (lvBytesTotal != undefined) {
    trace("Loaded "+lvBytesLoaded+" of "+lvBytesTotal+" bytes.");
    loadvars_pb.setProgress(lvBytesLoaded, lvBytesTotal);
    }
};
my_lv.onLoad = function(success:Boolean) {
    loadvars_pb.setProgress(my_lv.getBytesLoaded(), my_lv.getBytesTotal());
    delete timer_mc.onEnterFrame;
    if (success) {
    trace("LoadVars loaded successfully.");
    } else {
    trace("An error occurred while loading variables.");
    }
};
my_lv.load("[place a valid URL pointing to a text file here]");

See also
LoadVars.load(), LoadVars.sendAndLoad()

getBytesTotal Method

public getBytesTotal() : Number

Player version: Flash Player 6

Returns the total number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad(). This method returns undefined if no load operation is in progress or if a load operation has not started. This method also returns undefined if the number of total bytes can't be determined (for example, if the download was initiated but the server did not transmit an HTTP content-length).

Returns
Number — An integer.

Example
The following example uses a ProgressBar instance and a LoadVars object to download a text file. When you test the file, two things are displayed in the Output panel: When you test the file, two things write to the log file: whether the file loads successfully and how much data loads into the SWF file. You must replace the URL parameter of the LoadVars.load() command so that the parameter refers to a valid text file using HTTP. If you attempt to use this example to load a local file that resides on your hard disk, this example will not work properly because in test movie mode Flash Player loads local files in their entirety. To see this code work, add a ProgressBar instance called loadvars_pb to the Stage. Then add the following ActionScript to Frame 1 of the Timeline:
var loadvars_pb:mx.controls.ProgressBar;
var my_lv:LoadVars = new LoadVars();
loadvars_pb.mode = "manual";
this.createEmptyMovieClip("timer_mc", 999);
timer_mc.onEnterFrame = function() {
    var lvBytesLoaded:Number = my_lv.getBytesLoaded();
    var lvBytesTotal:Number = my_lv.getBytesTotal();
    if (lvBytesTotal != undefined) {
    trace("Loaded "+lvBytesLoaded+" of "+lvBytesTotal+" bytes.");
    loadvars_pb.setProgress(lvBytesLoaded, lvBytesTotal);
    }
};
my_lv.onLoad = function(success:Boolean) {
    loadvars_pb.setProgress(my_lv.getBytesLoaded(), my_lv.getBytesTotal());
    delete timer_mc.onEnterFrame;
    if (success) {
    trace("LoadVars loaded successfully.");
    } else {
    trace("An error occurred while loading variables.");
    }
};
my_lv.load("[place a valid URL pointing to a text file here]");

See also
LoadVars.load(), LoadVars.sendAndLoad()

load Method

public load(url:String) : Boolean

Player version: Flash Player 6 — Behavior changed in Flash Player 7.

Downloads variables from the specified URL, parses the variable data, and places the resulting variables in my_lv. Any properties in my_lv with the same names as downloaded variables are overwritten. Any properties in my_lv with different names than downloaded variables are not deleted. This is an asynchronous action.

The downloaded data must be in the MIME content type application/x-www-form-urlencoded.

This is the same format that is used by loadVariables().

Also, in files published for Flash Player 7, case-sensitivity is supported for external variables that are loaded with LoadVars.load().

This method is similar to XML.load().

Note: If a file being loaded contains non-ASCII characters (as found in many non-English languages), it is recommended that you save the file with UTF-8 or UTF-16 encoding as opposed to a non-Unicode format like ASCII.

When using this method, consider the Flash Player security model:

For Flash Player 8:

For more information, see the following:

For Flash Player 7 and later websites can permit cross-domain access to a resource via a cross-domain policy file. In SWF files of any version running in Flash Player 7 and later, url must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com.

In SWF files that are running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. A superdomain is derived by removing the left-most component of a file's URL. For example, a SWF file at www.someDomain.com can load data from sources at store.someDomain.com because both files are in the same superdomain of someDomain.com.

The value you pass for url must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com. If you want to load data from a different domain, you can place a cross-domain policy file on the server hosting the SWF file.

Parameters
url:String — A string; the URL from which to download the variables. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file.

Returns
Booleanfalse if no parameter (null) is passed; true otherwise. Use the onLoad() event handler to check the success of loaded data.

Example
The following code defines an onLoad handler function that signals when data is returned to the Flash application from a server-side PHP script, and then loads the data in passvars.php.
var my_lv:LoadVars = new LoadVars();
my_lv.onLoad = function(success:Boolean) {
    if (success) {
    trace(this.toString());
    } else {
    trace("Error loading/parsing LoadVars.");
    }
};
my_lv.load("http://www.helpexamples.com/flash/params.txt");

For another example, see the guestbook.fla file in the ActionScript samples folder. Here are some typical paths to this folder:

See also
XML.load(), LoadVars.loaded, LoadVars.onLoad, System.useCodepage

send Method

public send(url:String, target:String, [method:String]) : Boolean

Player version: Flash Player 6

Sends the variables in the my_lv object to the specified URL. All enumerable variables in my_lv are concatenated into a string in the application/x-www-form-urlencoded format by default, and the string is posted to the URL using the HTTP POST method. This is the same format used by loadVariables().The MIME content type sent in the HTTP request headers is the value of my_lv.contentType or the default application/x-www-form-urlencoded. The POST method is used unless GET is specified.

You must specify the target parameter to ensure that the script or application at the specified URL will be executed. If you omit the target parameter, the function will return true, but the script or application will not be executed.

The send() method is useful if you want the server response to:

A successful send() method call will always open a new browser window or replace content in an existing window or frame. If you would rather send information to a server and continue playing your SWF file without opening a new window or replacing content in a window or frame, then you should use LoadVars.sendAndLoad().

This method is similar to XML.send().

The Flash test environment always uses the GET method. To test using the POST method, be sure you are attempting to use it from within a browser.

When using this method, consider the Flash Player security model:

For more information, see the following:

Parameters
url:String — A string; the URL to which to upload variables.
target:String — A string; the browser window or frame in which any response will appear. You can enter the name of a specific window or select from the following reserved target names:
  • "_self" specifies the current frame in the current window.
  • "_blank" specifies a new window.
  • "_parent" specifies the parent of the current frame.
  • "_top" specifies the top-level frame in the current window.
method:String [optional] — A string; the GET or POST method of the HTTP protocol. The default value is POST.

Returns
Boolean — A Boolean value; false if no parameters are specified, true otherwise.

Example
The following example copies two values from text fields and sends the data to a CFM script, which is used to handle the information. For example, the script might check if the user got a high score and then insert that data into a database table.
var my_lv:LoadVars = new LoadVars();
my_lv.playerName = playerName_txt.text;
my_lv.playerScore = playerScore_txt.text;
my_lv.send("setscore.cfm", "_blank", "POST");

See also
LoadVars.sendAndLoad(), XML.send()

sendAndLoad Method

public sendAndLoad(url:String, target:Object, [method:String]) : Boolean

Player version: Flash Player 6 — Behavior changed in Flash Player 7.

Posts variables in the my_lv object to the specified URL. The server response is downloaded, parsed as variable data, and the resulting variables are placed in the target object.

Variables are posted in the same manner as LoadVars.send(). Variables are downloaded into target in the same manner as LoadVars.load().

When using this method, consider the Flash Player security model:

For Flash Player 8:

For more information, see the following:

For Flash Player 7 and later:

In SWF files that are running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. A superdomain is derived by removing the left-most component of a file's URL. For example, a SWF file at www.someDomain.com can load data from sources at store.someDomain.com because both files are in the same superdomain named someDomain.com.

The value you pass for url must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com. If you want to load data from a different domain, you can place a cross-domain policy file on the server hosting the SWF file.

This method is similar to XML.sendAndLoad().

Parameters
url:String — A string; the URL to which to upload variables. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file.
target:Object — The LoadVars or XML object that receives the downloaded variables.
method:String [optional] — A string; the GET or POST method of the HTTP protocol. The default value is POST.

Returns
Boolean — A Boolean value.

Example
For the following example, add a TextInput instance called name_ti, a TextArea instance called result_ta, and a Button instance called submit_button to the Stage. When the user clicks the Login button instance in the following example, two LoadVars objects are created: send_lv and result_lv. The send_lv object copies the name from the name_ti instance and sends the data to greeting.cfm. The result from this script loads into the result_lv object, and the server response displays in the TextArea instance (result_ta). Add the following ActionScript to Frame 1 of the Timeline:
var submitListener:Object = new Object();
submitListener.click = function(evt:Object) {
    var result_lv:LoadVars = new LoadVars();
    result_lv.onLoad = function(success:Boolean) {
    if (success) {
        result_ta.text = result_lv.welcomeMessage;
    } else {
        result_ta.text = "Error connecting to server.";
    }
    };
    var send_lv:LoadVars = new LoadVars();
    send_lv.name = name_ti.text;
    send_lv.sendAndLoad("http://www.flash-mx.com/mm/greeting.cfm", result_lv, "POST");
};
submit_button.addEventListener("click", submitListener);

To view a more robust example, see the login.fla file in the ActionScript samples folder. Typical paths to the ActionScript samples folder are:

See also
LoadVars.send(), LoadVars.load(), XML.sendAndLoad()

toString Method

public toString() : String

Player version: Flash Player 6

Returns a string containing all enumerable variables in my_lv, in the MIME content encoding application/x-www-form-urlencoded.

Returns
String — A string.

Example
The following example instantiates a new LoadVars() object, creates two properties, and uses toString() to return a string containing both properties in URL encoded format:
var my_lv:LoadVars = new LoadVars();
my_lv.name = "Gary";
my_lv.age = 26;
trace (my_lv.toString()); //output: age=26&name=Gary