Loading Variables from a Data Source

I l @ ve RuBoard

Loading Variables from a Data Source

Flash movies can load data from external data sources. You can use actions and methods to communicate with server-side scripts, XML files, and text files. The MovieClip object loads information into a movie, in a URL-encoded format, using the loadVariables , loadVariablesNum , loadMovie , and loadMovieNum methods. You can also use the load and sendAndLoad methods of the LoadVars object to get data from an external source. The XML and XMLSocket objects also have methods that let you communicate with external data sources, but the use of these objects is outside the scope of this book.

In the next exercise, you will use the sendAndLoad method of the LoadVars object to get data from a PHP file on a server. Depending on which instance of the PushButton component was clicked, the ActionScript you add might also send data to the PHP file, modifying its output. You should start this exercise with map1.fla open .

  1. Select frame 1 of the Actions layer, and add the following ActionScript:

      function getList(btn) {   trace(btn._name);   }   dataURL = "http://www.flashtfs.com/data/";  

    graphics/09fig11.gif

    Add this ActionScript before the ActionScript that you added in the previous exercise. Just add a new line before that code, and start typing.

    This is the getList function you assigned as the Click Handler for each instance of the PushButton component. If you use the same chunk of code in several places in your movie, it can be useful to turn that chunk of code into a function, which is simply a reusable chunk of code. You can then refer to the function instead of rewriting the code each time you want to use it. A function can also be useful when you need to make changes to the code; you only have to do it in one placethe function itself.

    The getList function has a single parameter, btn . When you click an instance of the PushButton UI component, it automatically sends the path of the instance, in dot syntax, along with the call to the function specified in the Click Handler parameter. For example, when you click the asia instance of the PushButton component, that instance calls the getList function as if you had added the following code to the onPress event for that symbol:

      getList(_level0.asia);  

    The _ level0 portion of this code specifies the level of the asia instance. You'll learn about levels in Lesson 11.

    The contents of the getList function are very simple right now. You've added only one line to the function:

      trace(btn._name);  

    This code triggers the trace action. The single parameter for the trace action can be any expression. In this case, the expression is btn._name , which will return the _name property, or instance name , of whatever instance called the getList function. The trace action then displays the result in the Output window, as you'll see in the next step.

    The last line of code you added sets the value of the dataURL variable to http://localhost/flashtfs/data/ . This URL is part of the Flash TFS Web siteit contains several PHP scripts, which you will use to send and load data. You will use the dataURL variable later in this lesson.

  2. Choose Control > Test Movie.

    graphics/09fig12.gif

    When you click one of the PushButton instances, a window should pop up displaying the instance name of the push button. That is the Output window, which is useful for displaying notes or messages when you test a movie. The window opens because the trace action, which is called as part of the getList function, prints something in the window. If the window is already open, the trace action simply prints its output in the open windowit won't open another window.

    You can use trace actions throughout your ActionScript to check values and to make sure the values are being set properly. In this case, the trace action should output the instance name of the PushButton instance that you click. For example, if you click the asia instance of the PushButton component, the word asia should appear in the Output window.

  3. Modify the getList function by adding the following ActionScript:

      locData = new LoadVars();   if (btn._name != "all" && btn._name != undefined) {   locData.location = btn._name;   }   locData.sendAndLoad(dataURL+"map.php", locData, POST);  

    graphics/09fig13.gif

    You should add this code following the line containing the trace action. After you add the code, your getList function should look like this:

      function getList(btn) {   trace(btn._name);   locData = new LoadVars();   if (btn._name != "all" && btn._name != undefined) {   locData.location = btn._name;   }   locData.sendAndLoad(dataURL+"map.php", locData, POST);   }  

    The first line of the code you just added creates a new instance of the built-in LoadVars object. This code should look somewhat familiar to youyou created several new object instances in Lesson 7. In this case, the constructor function that follows the new operator is LoadVars() . This code sets the name of the new instance of the LoadVars object to locData .

    The next three lines of code add a little bit of logic to the getList function. This if statement checks to see if the instance name of the PushButton you clicked ( btn._name ) is not "all" and undefined . The inequality operator ( != ) tests for inequality. So if the left side of the first expression ( btn._name ) is not equal to the right side ( "all" ), the expression will be true. The logical "and" operator ( && ) requires that both expressions be true in order to make the if statement's condition true. So the ActionScript inside the if statement will only be triggered if the instance name of the PushButton that calls getList is neither "all" nor undefined . If the condition is true, the location variable in the locData instance of the LoadVars object you created is set to btn._name .

    NOTE

    As you learned in Lesson 7, undefined is a special value in Flash. It is used to indicate that the value of a variable has not been set. So if no instance of the PushButton component triggered the getList function, which could happen if you simply call the function from a frame, the instance name of btn would be undefined .

    NOTE

    The location variable is not a built-in variable or property of the LoadVars object. See Appendix D for more information about the LoadVars object.

    The last line of code you added to the getList function uses the sendAndLoad method of the built-in LoadVars object to send the values of any variables in the locData instance of the object to a server-side script. If the instance name of the PushButton that called the getList function is neither all nor undefined , the locData object has a variable named location , with a value of the instance name of the button that called the function.

    This method also requests the resulting data set and places it inside the LoadVars object named locData . The parameters for the sendAndLoad method are the URL of the script and the object that you want to receive the resulting data. In this case the URL parameter is dataURL+"map.php" , which translates to http://www.flashtfs.com/data/map.php. The object that will receive the data returned by the server is locData , which is the same object that sent the data.

    NOTE

    When you view the Flash movie in your browser, as you will in Lesson 12, Flash might not be able to connect to the map.php file because Flash Player has some built-in security that disables connections to external data sources on other Web servers. But you should still be able to test the movie and view the data when you choose Control > Test Movie.

    Try viewing the URL specified in the URL parameter for the sendAndLoad method in your browser. The map.php file outputs a bunch of variable name/value pairs, in a format that Flash understands. When the file opens in your browser, choose View > Source (Microsoft Internet Explorer) or View > Page Source (Netscape Navigator) to view the source. The first couple of lines of the source should look something like this:

      &common0=African Elephant&   &latin0=Loxodonta africana&  

    graphics/09fig14.gif

    The first line of text generated by the PHP file creates a variable called common0 with a value of African Elephant :

      common0=African Elephant  

    This format is how you set up a variable in Flash, so that Flash understands the text from the PHP file as though it were a bunch of internal variables. The & 's in the text generated by the PHP file separate each of the variables.

    If you're curious , take a look at the source code for the PHP script. Open map.php from the Lesson09/Assets folder in a text editor such as Notepad (Windows) or SimpleText (Macintosh). The code looks like this:

      <?php   $link = mysql_connect("hostname", "username", "password";   $query = "SELECT animals.* FROM animals";   if (isset($location)) {   $query .= ",locations WHERE locations.name='$location' AND locations.ID=animals.LID";   }   $query .= " ORDER BY animals.common";   $result = mysql_db_query("zoomx", $query);   $c = 0;   while ($animals = mysql_fetch_array($result)) {   $output .= "&common$c=$animals[common]&\r\n";   $output .= "&latin$c=$animals[latin]&\r\n";   $output .= "&description$c=$animals[description]&\r\n";   $output .= "&image$c=$animals[image]&\r\n";   ++$c;   }   echo($output);   echo("&numAnimals=$c&");   ?>  

    graphics/09fig15.gif

    Don't worry if you don't understand all this codeyou don't have to be a PHP guru to work with Flash! You might notice that some of it looks a lot like ActionScriptthe two languages are actually quite similar. All this script does is connect to a MySQL database, get some records from that database, and then return the text you see when you view the source code in your browser. The script retrieves either all of the records in the database, or records for a specific location, depending on whether the $location variable (the location variable of the locData object, which was sent to the script) is set.

  4. Add a dynamic text box to the List layer.Set the variable for this text box to heading and set the X and Y to 315 and 40.

    NOTE

    The text box should be at least 200 pixels wide, but it should not extend beyond the right edge of the ListBox component instance in the List layer.

    graphics/09fig16.gif

    Use the text tool to add this text box. When you select the text tool from the toolbox, the Property inspector displays the text properties. Set the Text Type to Dynamic Text. Make sure the Font is set to Verdana, the Font Size to 12, and the Text (fill) Color to #CC0000 (red). You should also set the Line Type to Single Line, and make sure the Selectable button is not clicked.

    Compare the Property inspector with the figure above, and make sure the settings are the same.

  5. Add the following ActionScript to the if statement in the getList function in the Action layer:

      var subtitle = btn.getLabel();  

    graphics/09fig17.gif

    Add this code after the line already in the if statement. The function should look like this after you add the code:

      function getList(btn) {   trace(btn._name);   locData = new LoadVars();   if (btn._name != "all" && btn._name != undefined) {   locData.location = btn._name;   var subtitle = btn.getLabel();   }   locData.sendAndLoad(dataURL+"map.php", locData, POST);   }  

    The code you just added sets up a new local variable named subtitle . A local variable exists only inside the function, so if for some reason you add a variable called subtitle to another part of your code, this variable's value will not affect that variable's value. You can make a variable local by adding the var action to the beginning of the line that declares the variable name and value.

    The value for the subtitle variable is btn.getLabel(); . Each instance of the PushButton component is actually an instance of the built-in FPushButton object, so you can use the methods for that built-in object. The getLabel method gets the Label value of the specified PushButton instance ( btn ). The getLabel function will return the Label parameter's value for any instance that triggers the getList function, as long as the instance's name is not "all" or undefined . For example, if you click the americas instance of the PushButton component, the subtitle variable will have a value of "The Americas" .

    NOTE

    Appendix D lists more of the FPushButton object's methods and properties.

  6. Add this code after the if statement:

      else {   var subtitle = "Entire Zoo";   }  

    graphics/09fig18.gif

    Add this code following the curly brace (}) that ends the if statement. After you add the ActionScript, the function should look like this:

      function getList(btn) {   trace(btn._name);   locData = new LoadVars();   if (btn._name !="all" && btn._name != undefined) {   locData.location = btn._name;   var subtitle = btn.getLabel();   } else {   var subtitle = "Entire Zoo";   }   locData.sendAndLoad(dataURL+"map.php", locData, POST);   }  

    The else statement provides a value for the subtitle variable if the instance name of the PushButton that calls the getList function is "all" or undefined . If you click the "all" instance of the PushButton component, or you call the function from the timeline, the subtitle variable will have a value of "Entire Zoo" .

  7. Now add the following code to the getList function:

      heading = "Animal List: " + subtitle;  

    graphics/09fig19.gif

    This code should be added after the if statement. Your almost-complete getList function should look like this:

      function getList(btn) {   trace(btn._name);   locData = new LoadVars();   if (btn._name != "all" && btn._name != undefined) {   locData.location = btn._name;   var subtitle = btn.getLabel();   } else {   var subtitle = "Entire Zoo";   }   locData.sendAndLoad(dataURL+"map.php", locData, POST);   heading = "Animal List: " + subtitle;   }  

    This ActionScript sets the value of the heading variable, which is not a local variable (no var action). That's the variable name you set for the dynamic text box you added earlier in this exercise, so this line of code sets the value of the text displayed in that text box. The value of the heading variable depends on the value of the subtitle variablethe addition operator ( + ) adds the value of the subtitle variable to the string "Animal List: " . If the subtitle variable has a value of "Entire Zoo", the heading variable will have a value of "Animal List: Entire Zoo" .

  8. Choose Control > Test Movie. Save the file as map2.fla.

    graphics/09fig20.gif

    When you click one of the PushButton instances, the instance name should still appear in the Output window. Additionally, the dynamic text box that has a variable name of heading should change, depending on which button you click.

    After you test each button, close the Test Movie window and save your file as map2.fla in the FlashTFS folder. Right now the ActionScript in the getList function only requests the data from the map.php file on the server. You still have to add more code to display the data that Flash receives when it's loaded. You'll do that in the next exercise.

I l @ ve RuBoard


Macromedia Flash MX. Training from the Source
Macromedia Flash MX: Training from the Source
ISBN: 0201794829
EAN: 2147483647
Year: 2002
Pages: 115
Authors: Chrissy Rey

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