USING THE LOADVARS OBJECT


You will use the LoadVars object when working with data in the URL string format. This object enables you to load variable data from a text file or send and load variable data to and from a server-side script.

NOTE

While variable data contained in a text file can be loaded into Flash, Flash cannot save data to a text file directly; you must use a server-side script to do that.


Creating a LoadVars object in Flash is simple. Take a look at the following example:

 container = new LoadVars(); 

This creates a new LoadVars object named container . To load variables from a URL into a LoadVars object, use the load() method:

 container.load("http://www.myDomain.com/myFile.txt"); 

TIP

At any time you can get the total number of bytes loaded so far or the total bytes that will be loaded using the getBytesLoaded() and getBytesTotal() methods of the LoadVars object.


When data has been loaded into a LoadVars object, you can access it by referencing the name of the particular LoadVars object that contains the data you want, followed by the variable name of that piece of data. For example, if you were to load the following string into a LoadVars object named myData:

name=Jobe&age=25&wife=Kelly

These variable values could be referenced as follows:

 myData.name  myData.age  myData.wife 

For example:

 usersAge = myData.age; 

Here, usersAge would have a value of 25. In the same manner, a variable value in a LoadVars object (myData ) can be set from within a script in Flash in the following manner:

 myData.age = 45; 

This means that variable values inside a LoadVars object can be set not only by loading external data into the object but also by setting its value internally (using a script inside the movie);

TIP

When loading variables into a LoadVars object, Flash will overwrite variable values where they may already exist in the object and append new variable values that don't already exist.


If you wish to send the variables in a LoadVars object to a server-side script for processing, you would use the send() method. That syntax is as follows:

 myLoadVarsObject.send("http://www.mydomain.com/process.cfm"); 

A response is not sent back to Flash when you use this method which means you would only use it to send variable data to the server for processing.

The sendAndLoad() method allows you to specify a LoadVars object whose contents you want to send and the LoadVars object in which you want the response to load:

 myLoadVarsObject.sendAndLoad("http://mydomain.com/process.asp",  receivingLoadVarsObject); 

In this case, the variables in myLoadVarsObject are sent to the URL shown for processing. The server will send data back to Flash, and that data will be loaded into receivingLoadVarsObject . At that point, you can work with the receivingLoadVars object to extract the data the server sent back. If you want to send variables in a LoadVars object and have that same object receive the data the server sends back, simply use the load() method (which we'll describe in the following exercise).

Using the toString() method of the LoadVars object, you can create a URL-formatted string that represents the variables/values contained in the object.

graphics/11fig04.gif

The LoadVars object has two properties: contentType and loaded . The contentType property (which you can change before sending out variables) simply gives you the mime type specified in the HTTP header of the loaded document. The loaded property simply returns true if data has finished loading into the object, false if it has not, and undefined if a load() method has not yet been invoked.

There is only one event available to the LoadVars object: onLoad . You would use this event to call a function when data has finished loading into the object. Each time data is loaded into the object, this event is fired again.

To load variables from a specified URL into a LoadVars object and then have it call a function when loading is complete, you must:

  1. Define a function

  2. Create a new LoadVars object using the new LoadVars constructor

  3. Specify the function to be called when the loading has completed

  4. Invoke the load() method of the LoadVars object

For example:

 function myFunction(){    trace("Data is loaded");  }  container = new LoadVars();  container.onLoad = myFunction;  container.load("http://www.somedomain.com/myFile.asp"); 

In this example, myFunction() is called when a string of data from the specified URL has been completely loaded into the container LoadVars object.

NOTE

If you're familiar with Flash 5's use of the loadVariables() method, you should know that while it still works in Flash MX, it's preferable to use LoadVars objects.


In the following exercise, you'll create a simple polling system using a LoadVars object. This object will send and load data to and from an ASP page in the URL string format. This page contains a server-side script that enables it to read and write to a Microsoft Access database. When variable data is sent to the ASP page, it interprets it and updates the values in the database accordingly. When a LoadVars object requests that data be loaded into it from the ASP page, the page is set up so that it gets the data from the various fields in the database, encodes that data into the URL string format, and then sends that data to the LoadVars object.

You will find this scripted page (poll.asp) and the accompanying database (poll.mdb) in the Lesson11 folder on your CD-ROM. To complete this lesson successfully, you will need access to a Windows server so that the server-side script on the ASP page can be executed. Before you begin this exercise, you will need to upload poll.asp and poll.mdb to a Windows server and make a note of their location (URL).

  1. Open poll1.fla in the Lesson 11/Assets folder.

    We've already created the layers, frames, frame labels, and movie clips you'll need so that you can focus on the ActionScript.

    With the timeline at Frame 1, you'll notice the following text: "What was the best movie of 2001?" Below this text is some space, then a Submit button. You will place four Radio Button components in the empty space between these two elements. These radio buttons will represent the selection method for your choice of the best movie of 2001. When a user presses the Submit button, the movie will execute a script, sending data to the server (based on which radio button is selected) and at the same time moving the playhead to Frame 3, labeled waiting, where it will wait for a response from the server. When a response is received (data is loaded into a LoadVars object), the movie will move to the frame labeled display. This frame will contain a script used to interpret the response from the server (data will be extracted from the LoadVars object). This data will then be used to determine the percent of the total number of votes that each of the four movies listed has received. Each movie's overall percentage value will then be displayed in a text field as well as graphically, using simple bar graphs.

    graphics/11fig05.gif

  2. Move the playhead to Frame 1 and select the frame in the layer called Text and Buttons.

    You will add four instances of the Radio Button component to this layer (beneath the question but above the Submit button).

  3. Open the Components panel. Locate the Radio Button component and drag four instances of it onto the stage. Align these four components in a vertical column under the question on the screen.

    You have just added four Radio Button components to the stage. If you select one of them and look at the Property inspector, you'll see a list of that component's properties, all of which are editable. The first property, Label, is the name that will be displayed next to the button. The next property, Initial State, is a Boolean value that determines whether this radio button should be selected or unselected initially. The Group Name property is a name that binds groups of radio buttons together. The four radio buttons we have added will be part of the same group; thus, each of their Group Name property values will be the same (we'll use the default value of radioGroup for all four buttons). Only a single radio button from the group can be selected at a time. In addition, each radio button in the group is assigned an associated value (its Data property). When one of the radio buttons is selected, its Data property value becomes the overall group's data value. Thus, if a radio button is selected and its Data property value is 47, the group's data value is updated to 47 as well (a fact that will be important to remember for this project). Below the Data property in the Property inspector, you'll see the Label Placement property. This property is used to determine whether the radio button's label should be left- or right-justified. Finally, the Change Handler property lets you define a function that you want to call when the button is pressed; you can leave this blank.

    graphics/11fig06.gif

  4. Select the top radio button and change its Label property to "A Beautiful Mind." Change the Label properties of the next three radio buttons to "Lord of the Rings", "Harry Potter", and "American Pie II" respectively.

    As you change the label names of the radio buttons (from top to bottom on the screen), you should be able to see that the text is updated in the component itself.

    NOTE

    If this doesn't happen, choose Control > Enable Live Preview.

  5. Change the Data property of the four Radio Button components to 1, 2, 3, and 4, from top to bottom.

    When the movie is published and a radio button is selected, its Data property value is set as the data value of the radioGroup. You retrieve this data value for use at any time by invoking the getData() method of the Radio Button component object. For example, if a radio button with a Data property value of 3 was selected, and this radio button was part of a group of radio buttons with a group name of radioGroup, the following syntax:

     selectedValue = radioGroup.getData(); 

    would assign a value of 3 to selectedValue .

  6. With the Actions panel open, select Frame 1 in the Actions layer and add stop() ;

    This stop() action prevents the movie from playing past Frame 1 until we instruct it to do so.

  7. With Frame 1 still selected, add the following line of script:

     pollURL = "http://www.myDomain.com/poll.asp"; 

    This creates a variable name pollURL and assigns it a value that represents the location (URL) of the poll.asp page you uploaded to your server at the beginning of this exercise. (The URL shown should be replaced with the actual location of poll.asp, as it resides on your server.)

  8. Next, add this line of ActionScript:

     poll = new LoadVars(); 

    This creates a new LoadVars object. With this object, we can load data from a remote location and make use of the convenient methods and properties described earlier in this lesson.

  9. Define the pollLoaded() function by adding the following ActionScript at the end of the current script:

     function pollLoaded() {    _root.gotoAndStop("display");  } 

    This function is used to move the playhead to the frame labeled display. (The next step explains when this function gets called.)

  10. To associate the function we just defined with the onLoad event of the poll LoadVars object, add the following line of ActionScript:

     poll.onLoad = pollLoaded; 

    This script says that when the last byte of data is completely loaded into the poll LoadVars object, the pollLoaded() function will be called. Thus, when the data has finished loading, the timeline will move to the frame labeled display (since that function is set up to move the timeline to that label). In a moment, we'll add a script at the display frame that will use the loaded data to display the results in several bar graphs.

  11. Next, add this function definition just below the last line of script:

     function submitChoice() {    var choice = radioGroup.getData();    poll.load(pollURL + "?choice=" + choice);    _root.gotoAndStop("waiting");  } 

    graphics/11fig07.gif

    This function which is used to submit the user's choice for best movie of 2001 is called when the Submit button is clicked.

    The first line of the function definition creates a local variable named choice . This variable is assigned the current data value of the radioGroup group of radio buttons. Thus, if the user selected the second radio button, choice would have a value of 2 .

    The next line of ActionScript invokes the load() method of the poll LoadVars object. Using an expression, the URL of the poll.asp page is specified (pollURL ), and the variable choice is added to the end of the string in order to send this to the server using the GET method of transferring variable data. If the user pressed Radio Button 3, this argument would look something like the following: "http://www.mydomain.com/poll.asp?choice=3". Remember, everything after the question mark in the above argument is a variable. In this case, we're sending a vote (choice=3 ) to the poll.asp page. That page will then update the values in the database based on this vote and load the results into the poll LoadVars object. Those results are then used in the actions described in Step 14.

    graphics/11fig08.gif

    The final line of script in this function tells Flash to go to the frame labeled waiting. The movie will stay on this frame until the data is loaded back into Flash from the server. At that point, the pollLoaded() function will be called (as described in the previous step), moving the timeline to the frame labeled display.

  12. With the Actions panel open, select the Submit button and add the following script:

     on (release) {    submitChoice();  } 

    The submitChoice() function we defined in the previous step is executed when the button is clicked.

  13. Move the playhead to the frame labeled display.

    On this frame you'll see four movie clip instances with horizontal bars in them, one bar graph for each movie on which the user is voting. All of these are instances of the same movie clip: Their instance names are barGraph1, barGraph2, barGraph3, and barGraph4. Note that all of these instance names end with numbers: These are used to display the results of the poll. Each of these instances includes two text fields topPercent and bottomPercent that are used to display a textual representation of the percent. Both of these text fields display the same text; bottomPercent is simply there to provide a slight shadow effect behind topPercent. This movie clip also contains a horizontal bar with an instance name of bar. It will be horizontally scaled based on the value of the percent.

  14. Select the frame in the Actions layer and add this loop:

     for (i=1; i<=4; ++i) {    var graphName = "barGraph" + i;    var votes = poll["item" + i + "total"];    var totalVotes = poll.totalVotes;    var percent = Math.round((votes / totalVotes) * 100);    _root[graphName].bar._xscale = percent;  } 

    graphics/11fig09.gif

    When the playhead has made it to this frame label (display), it means the user has submitted his or her choice and the server has accepted it, added it to the current results, and loaded the resulting data into the poll LoadVars object. You'll remember that in Steps 9 and 10, we scripted our movie so that it would move to this frame label only after the resulting data from the server had been loaded completely into the poll LoadVars object. The script on this frame will now use that data. The variables loaded from the remote script into the LoadVars object are named totalVotes , item1total , item2total , item3total , and item4total . Obviously, totalVotes has a numeric value representing the total number of all votes submitted (which will be used in a moment to figure percentage values). The other variables hold the number of individual votes that each of the movies received. Since these variables have been loaded into the poll LoadVars object, you can access their values using the following syntax:

     poll.totalVotes  poll.item1total  poll.item2total  poll.item3total  poll.item4total 

    The loop in the above script calculates the percentage of votes received by each movie and scales the bar in the appropriate movie clip instance based on that number. The first line of script in the loop defines the variable called graphName . Since the value of this variable is based on the concatenation of the string "barGraph" with the current value of i , it is actually a reference to the name of the movie clip instance that will be worked with during the current loop (barGraph1, barGraph2, and so on). Once again, using the value of i , the next action in the loop sets a variable called votes equal to the total number of votes for the current item (poll.item1total , poll.item2total , and so on). Then, a variable called totalVotes is assigned a value that represents the total number of votes cast for all of the movies. Next, the percent variable is calculated by dividing the current item's number of votes by the total votes and multiplying by 100. This is then rounded using the Math.round() method of the Math object. Finally, the bar clip in the current movie clip (as referenced by the current value of graphName ) is scaled to match the percent value. This loop will repeat these actions four times, scaling each of the bar graphs in the process.

    graphics/11fig10.gif

    NOTE

    For more information about loops, see Lesson 10, Automating Scripts Using Loops.

  15. Add these two lines of ActionScript to the end of but within the loop:

     _root[graphname].topPercent.text = percent + "%";  _root[graphname].bottomPercent.text = percent + "%"; 

    The text to be displayed in the topPercent and bottomPercent text fields, above the scaled bar movie clip instance, is set using the value of the percent variable and concatenating "%" to the end of it.

  16. Choose Control > Test Movie to test your work. Select a movie radio button and press the Submit button.

    When you press the Submit button, your choice is sent to the poll.asp page, which then updates the database and returns the results of the poll to the poll LoadVars object. Your movie then moves to the frame labeled display and shows you the results!

  17. Close the test movie and save your work as poll2.fla.

    You have just completed a basic application that uses the LoadVars object to talk to external scripts. You can now use this knowledge to build more complex and useful applications.



Macromedia Flash MX ActionScripting Advanced. Training from the Source
Macromedia Flash MX ActionScripting: Advanced Training from the Source
ISBN: 0201770229
EAN: 2147483647
Year: 2002
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net