Flash CS4 Professional ActionScript 2.0

Using the LoadVars class

If you are publishing to Flash Player 6 or later and want more flexibility than loadVariables() offers, you can use the LoadVars class instead to transfer variables between a SWF file and a server.

The LoadVars class was introduced in Flash Player 6 to provide a cleaner, more object-oriented interface for the common task of exchanging CGI data with a web server. Advantages of the LoadVars class include the following:

  • You don't need to create container movie clips for holding data or clutter existing movie clips with variables specific to client/server communication.
  • The class interface is similar to that of the XML object, which provides some consistency in ActionScript. It uses the methods load(), send(), and sendAndLoad() to initiate communication with a server. The main difference between the LoadVars and XML classes is that the LoadVars data is a property of the LoadVars object rather than of an XML Document Object Model (DOM) tree stored in the XML object.
  • The class interface is more straightforward--with methods named load, send, sendAndLoad--than the older loadVariables interface.
  • You can get additional information about the communication, using the getBytesLoaded and getBytesTotal methods.
  • You can get progress information about the download of your data (although you can't access the data until it is fully downloaded).
  • The callback interface is through ActionScript methods (onLoad) instead of the obsolete, deprecated onClipEvent (data) approach required for loadVariables.
  • There are error notifications.
  • You can add custom HTTP request headers.

You must create a LoadVars object to call its methods. This object is a container to hold the loaded data.

The following procedure shows how to use ColdFusion and the LoadVars class to send an e-mail from a SWF file.

NOTE

 

You must have ColdFusion installed on your web server for this example.

 To load data with the LoadVars object:

  1. Create a CFM file in Macromedia Dreamweaver or in your favorite text editor. Add the following text to the file:
    <cfif StructKeyExists(Form, "emailTo")>
    <cfmail to="#Form.emailTo#" from="#Form.emailFrom#" subject="#Form.emailSubject#">#Form.emailBody#</cfmail>
    &result=true
    <cfelse>
    &result=false
    </cfif>
    
    
  2. Save the file as email.cfm, and upload it to your website.
  3. In Flash, create a new document.
  4. Create four input text fields on the Stage, and give them the following instance names: emailFrom_txt, emailTo_txt, emailSubject_txt, and emailBody_txt.
  5. Create a dynamic text field on the Stage with the instance name debug_txt.
  6. Create a button symbol, drag an instance on to the Stage, and give it an instance name of submit_btn.
  7. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions) if it isn't already open.
  8. Enter the following code in the Actions panel:
    this.submit_btn.onRelease = function() {
        var emailResponse:LoadVars = new LoadVars();
        emailResponse.onLoad = function(success:Boolean) {
        if (success) {
                debug_txt.text = this.result;
        } else {
                debug_txt.text = "error downloading content";
        }
        };
        var email:LoadVars = new LoadVars();
        email.emailFrom = emailFrom_txt.text;
        email.emailTo = emailTo_txt.text;
        email.emailSubject = emailSubject_txt.text;
        email.emailBody = emailBody_txt.text;
        email.sendAndLoad("http://www.yoursite.com/email.cfm", emailResponse, "POST");
    };
    
    

    This ActionScript creates a new LoadVars object instance, copies the values from the text fields into the instance, and then sends the data to the server. The CFM file sends the e-mail and returns a variable (true or false) to the SWF file called result, which appears in the debug_txt text field.

    NOTE

     

    Remember to change the URL www.yoursite.com to your own domain.

  9. Save the document as sendEmail.fla, and then publish it by selecting File > Publish.
  10. Upload sendEmail.swf to the same directory that contains email.cfm (the ColdFusion file you saved and uploaded in step 2).
  11. View and test the SWF file in a browser.

For more information, see the LoadVars entry in the ActionScript 2.0 Language Reference.

Flash Player 8 and later supports the onHTTPStatus event handler for the LoadVars class, XML class, and MovieClipLoader class to allow users to access the status code from an HTTP request. This allows developers to determine why a particular load operation may have failed instead of only being able to determine that a load operation already has failed.

The following example shows how you can use the LoadVars class's onHTTPStatus event handler to check whether a text file successfully downloaded from the server and what the status code returned from the HTTP request was.

 To check HTTP status with the LoadVars object:

  1. Create a new Flash document and save it as loadvars.fla.
  2. Add the following ActionScript to Frame 1 of the main Timeline:
    this.createTextField("params_txt", 10, 10, 10, 100, 21);
    params_txt.autoSize = "left";
    
    var my_lv:LoadVars = new LoadVars();
    my_lv.onHTTPStatus = function(httpStatus:Number) {
        trace("HTTP status is: " + httpStatus);
    };
    my_lv.onLoad = function(success:Boolean) {
        if (success) {
            trace("text file successfully loaded");
            params_txt.text = my_lv.dayNames;
        } else {
            params_txt.text = "unable to load text file";
        }
    };
    my_lv.load("http://www.helpexamples.com/flash/404.txt");
    /* output:
        Error opening URL "http://www.helpexamples.com/flash/404.txt"
        HTTP status is: 404
    */
    
    

    The previous code creates a new text field on the Stage and enables text field autosizing. Next, a LoadVars object is created and two event handlers: onHTTPStatus and onLoad. The onHTTPStatus event handler (supported in Flash Player 8 and later) is invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has completed. The value passed to the onHTTPStatus event handler function (httpStatus in the previous code) contains the HTTP status code definition for the current load operation. If the SWF file was able to successfully load the text file, the value of httpStatus is set to 200 (HTTP status code for "OK"). If the file didn't exist on the server, the value of httpStatus is set to 404 (HTTP status code for "Not Found"). The second event handler, LoadVars.onLoad(), gets called after the file has finished loading. If the file successfully loaded, the value of the success parameter is set to true, otherwise the success parameter is set to false. Finally, the external file is loaded using the LoadVars.load() method.

  3. Select Control > Test Movie to test the Flash document.

    Flash displays an error message to the Output panel stating that it was unable to load the image because it doesn't exist on the server. The onHTTPStatus event handler traces the status code of 404 since the file could not be found on the server, and the onLoad event handler sets the params_txt text field's text property to "unable to load text file."

CAUTION

 

If a web server does not return a status code to the Flash Player, the number 0 is returned to the onHTTPStatus event handler.