Loading Text Data with LoadVars

     

Loading Text Data with LoadVars

To get a piece of information from the server, you need to create the LoadVars object and then execute a load() method as follows :

 var myLoadVars = new LoadVars(); myLoadVars.load("data.txt"); 

The preceding code uses data.txt as an example of the filename to be loaded. This text file should have a special format, consisting of any number of name /value pairs: propertyName = propertyValue & . The two special characters here are the equal sign and the ampersand. The equal sign divides the property name and its value. The ampersand serves as a delimiter between name/value pairs. You can place as many name/value pairs in the text file as you like. The following is an example:

 a=7&b=42.8&c=Hello World!& 

(The final ampersand in the preceding line is not necessary but also does no harm.)

Do not use quotation marks to indicate strings: The quotation marks will be loaded as part of the property value. In addition, you can have line breaks inside strings, and they will be included in the property value, as in the following example:

 a=7&myString=This is a test of a multi-line variable passed to Flash& 

When this data is loaded, an attribute is added to the LoadVars object for each name/value pair. For instance, in the previous examples, the attribute a is added with the value 7 . You can display the a attribute in the Output window like this:

 trace(myLoadVars.a); 

Completing LoadVars

When you use the load() method, you don't see the results instantly. First, Flash requests the file from the server; then it must wait until the file arrives. Only then can it read the information in the file. This process could take a fraction of a second or several seconds.

So how do you know when the load() is complete? There are two ways.

You can just check to see whether the loaded property of the LoadVars object is true, but doing so requires you to loop and check the loaded property over and over again. Instead, you can use the onLoad event of the LoadVars object to create a function that executes automatically when the loading is done. Here is an example:

 myLoadVars = new LoadVars(); myLoadVars.onLoad = function() {     results = myLoadVars.toString(); } myLoadVars.load("loadVarsData.txt"); 

For more on events, see "Using Event Handlers to Trigger Action," page 500 , in Chapter 20.


The preceding code segment, which you can find in the button in the sample movie named load.fla on the CD, sets the value of the variable results to the result of the toString() function. This function, when used with a LoadVars object, shows you the properties of the object in one long string. The result is as follows:

 c=Hello%20World%21&b=42%2E8&a=7&onLoad=%5Btype%20Function%5D 

The file loadVarsData.txt contains the following:

 a=7&b=42.8&c=Hello World!& 

The display order of the toString() method is the reverse of the order in which the variables are stored in the file. Also, the characters are converted to use escape characters similar to those used with Internet data. For instance, %20 stands for hexadecimal number 20, which is the decimal number 32, which is the character code for a space.

While you're waiting for a large data file to load, you can use ActionScript to track its progress. The LoadVars object includes getBytesTotal() and getBytesLoaded() methods . You can use them to create a progress display. However, in most cases, the data file is too small to need such a display.

Security Issues

By default, the Flash Player can read information only from the same domain where the Flash movie is located. (FP7 is stricter than FP6 in its interpretation of what "the same domain" means.) This is not true when you're testing a movie in Flash MX or using a standalone projector, but this restriction is enforced when you're viewing the movie over the Internet. So, by default, you cannot use Flash to load information from one Web site to another. A policy file on the server from which you're downloading can overcome this limitation.


For more on security, see "New Security Rules," page 330 , in Chapter 14, "What's New in Flash MX 2004?." Also see crossDomainPolicyFiles.htm and security2004.htm on the CD accompanying this book.


The LoadVariables() Global Function

It is worth mentioning the LoadVariables() global function, which is the "old-school" way of getting information from the server.

The use of LoadVariables is demonstrated in onData.fla on the CD accompanying this book.


LoadVariables() is similar to the LoadVars object, but instead of storing the data it receives inside an object, it creates and populates variables of the movie clip it is in, or the root level if it is at the root level. It looks like this:

 this.LoadVariables("data.txt"); 

If the data.txt file is the same as in the previous example, variables a , b , and c will be created and populated .

You'll discover two major disadvantages to using LoadVariables() . The data is scattered into variables at the current level, rather than stored neatly inside the LoadVars object. The other disadvantage is that there is no event that can be used to deal with the variables when they have been loaded. That is, LoadVariables() has no event comparable to the onLoad event for LoadVars . Instead, to get a callback when variables have loaded, you must use onClipEvent( data ) , which is not always convenient .

An even more serious problem with LoadVariables() is that when you use it to send data (with an optional second parameter of POST or GET ), it sends all the variables from the current timeline. This means you usually must create a special movie clip to hold only the data that LoadVariables() should send. LoadVars is much easier to deal with in such situations. You'll learn how to use LoadVars to send information back to the server later in this chapter.

Loading Dynamic Data with LoadVars

You can also use the LoadVars object to get data from a dynamically generated source. To accomplish this, you must write server-side programs, also called Common Gateway Interface scripts, or CGI scripts. CGI scripts are written with a variety of languages, such as Perl, C, and Java. Because teaching you any of these languages is beyond the scope of this book, I'll try to keep the examples as simple as possible. I'll use Perl because it is widely available and easy to understand.

Consider the example of getting the current server time. A Perl program to get the current server time and return it (time.pl on the CD) looks like this:

 #!/usr/bin/perl  # tell Unix systems where Perl interpreter is use CGI;  # use CGI.pm for easy parsing $query = new CGI;  # create query object print $query->header({"Content-Type: text/html"});  # declare content type $time = localtime(); print "$time\n"; # \n is equivalent to a carriage return in the HTML exit 0; 

NOTE

In Perl, pound signs ( # ) precede comments. The "shebang" line (for example, #!/usr/bin/perl ”the name is related to "bang," meaning "exclamation point") is a special case, used by Unix systems to locate the Perl interpreter. When I quote lines of Perl programs, I leave out the comments, except the shebang line.


The first line ( #!/usr/bin/perl ), the "shebang" line, is required on Unix systems, to tell the server where the Perl interpreter is. On Windows systems running ActivePerl, you may not need a shebang line at all, or you may need a different shebang line.

The next line ( use CGI; ), as the comment notes, tells the script to use the CGI.pm module, a Perl5 CGI library which provides robust parsing and interpreting of query strings passed to CGI scripts.

The third line ( $query = new CGI; ) creates a query object, through which you reference CGI.pm functions.

The fourth line ( print $query->header({"Content-Type: text/html"}); ) "prints" (which really just means "outputs," in this case to the browser) a header line, telling the browser what kind of content to expect.

The heart of the program is the last three lines, which get the local server time and store it in a variable ( $time ), print the variable to the browser, and exit.

If you want to try this Perl program on your server, you need to take several steps. You can find this script, named time.pl, on the CD. Upload it to your Web server. If your server allows CGI scripts to work only in a special cgi-bin directory, you must place it there. You may have to set the permissions of the file to allow it to execute.

Creating a CGI program

If you are already lost, you have probably never created a CGI program. I strongly recommend that you get help from someone with CGI experience. Slight differences in server configurations could make running CGI scripts impossible if you don't have the help of someone with experience.


NOTE

A CGI script file from a Unix system may not run on a Windows system, because of the Unix line breaks in the file. The problem can be corrected by opening and re-saving the file with a Windows text editor.


If you want to teach yourself Perl, check out " Sams Teach Yourself Perl in 21 Days ," by Laura Lemay, Richard Colburn, and Robert Kiesling, ISBN 0672320355.


Now point your browser to the Web location of the CGI program. You should see a page that looks something like this:

 Sat Jan 24 12:13:02 2004 

If you see an error message, perhaps your server is not configured to run CGI programs. Or you may have not set the permissions properly for the directory in which the CGI program resides. Permissions may have to be configured both for the operating system and for the Web server. There are also other minor reasons why the Perl program might not work: Perl is not installed on the server; it is at a different location than /usr/bin/perl; the time.pl file was not uploaded as text; and so on. Finding someone who has used such programs before is the best way to solve these problems.

Now that you have a Perl program that generates a simple Web page that a browser can use, you can alter it so that Flash can use it.

The first step is to use the proper MIME type for the returned information. This is the fourth line of the code. Right now it is text/html , but you want it to be application/x-www-form-urlencoded .

The next step is to format the output in the propertyName=propertyValue format. Assume that the movie is looking for the variable currentTime . Here is the resulting program (flashtime.pl on the CD):

 #!/usr/bin/perl use CGI; $query = new CGI; print $query->header({"Content-Type: application/x-www-form-urlencoded"}); $time = localtime(); print "currentTime=$time"; exit 0; 

For your Flash movie to read this data, use a LoadVars object. As usual, you have to do three things to use LoadVars : create the LoadVars object, create an onLoad event for the LoadVars object, and execute a load() for the LoadVars object. Using a button with the instance name getTime_btn to execute the load() , the following code performs these three actions:

 myLoadVars = new LoadVars(); myLoadVars.onLoad = function() {         currentTime = this.currentTime; // "this" is myLoadVars } getTime_btn.onRelease = function () {     myLoadVars.load("flashtime.pl"); } 

The preceding code assumes that flashtime.pl is in the same directory as the SWF. If that is not the case, you need to provide a full URL to the Perl script.

You can see this code in the sample movie flashtime.fla. When the user presses the button, the movie calls out to flashtime.pl and gets the value it returns. The result should be something like currentTime=Sat Jan 24 12:13:02 2004 .

Then the myLoadVars property currentTime ( this.currentTime on line three in the preceding program) is copied to the root-level variable currentTime . This variable is linked to a dynamic text field, so you can see the result.

To get this movie working on your server, you need to upload flashtime.pl, flashtime.html, and flashtime.swf. They should all be placed in the same directory. You may need to set permissions for the directory, so that Perl scripts can run there.

The time displayed in the Flash movie is a reflection of the real time on the server. So the time is different each time you run the movie.

Setting the time is the simplest example of using dynamic information. From here, using such information all depends on your ability as a server-side programmer (or your connections with one). You can replace this simple Perl program with one that reads from a database and returns some complex data. For instance, it could return a random set of trivia questions or the latest stock quotes.

Sending email directly from Flash is another example of what can be done with Perl and CGI. See flashEmail.fla, flashEmail.pl, and flashEmail.html on the CD accompanying this book. (This script uses Unix sendmail and doesn't work on systems that don't support this capability. )


Sending Data with LoadVars

Sending information back to the server from Flash is similar to sending it back to the server from an HTML page. A CGI program must be at the other end to accept and record the information sent. Either of two commands may be used: GET or POST .

The GET method is the simplest. You can see it clearly in the Address field of your browser when it's in use. For example, this field might contain a URL that uses GET to send information to the server:

http://myserver.com/myscript.cgi?id=Mike&password=secret&

The preceding line of code sends two pieces of information to the script named myscript.cgi. It is up to that script to do something with the data.

The following example (collect.pl on the CD) is such a script. This Perl script grabs the GET input string and writes it to a file named Collect.txt. It also returns the text success! to the browser.

 #!/usr/bin/perl use CGI; $q = new CGI; $id = $q->param('id'); $password = $q->param('password'); open(OUTFILE,">>collect.txt"); print OUTFILE "$id\t$password\n"; close(OUTFILE); print $q->header({"Content-Type: text/html\n\n"}); print "success!"; exit 0; 

The original URL could come from something that the user hand-typed, from a standard HTML link, or from an HTML form using the GET method.

The data is taken from the portion of the URL after the question mark, also called the query string , represented in the preceding Perl script by the CGI object ( $q ). The open command opens the file named collect.txt with a >> option, which means that new data will be appended to the existing data in the file.

NOTE

The collect.txt file must already exist before you run collect.pl. The Perl script does not create collect.txt if it does not already exist.


The information is then written out, followed by a new line character. After the file is closed, the word success! is written out to the browser. This message replaces the current Web page in the browser. It gives you an indication that the CGI program did its job.

To get this script working on your server, you need to upload the collect.pl file and the empty text file collect.txt. As usual, the directory (and perhaps individual file) permissions need to be correctly configured. You can then test them in your browser by entering different text after the question mark in the URL. Whatever you put there should be recorded in the file.

If you cannot write to the file, the most likely problem is incorrect directory or file permissions. It could also be that the Perl script needs to specify the full local path to the collect.txt file (something along the lines of c:\inetpub\mydomain\cgi-bin\collect.txt , for example), rather than just the file name.

You can write to this file with Flash by using a LoadVars object. In addition to a load() method, LoadVars also has a send() method. The following ActionScript, attached to a button, collects three variable values in a LoadVars object and sends them to the CGI script:

 on (release) {     myLoadVars = new LoadVars();     myLoadVars.name = username;     myLoadVars.age = userage;     myLoadVars.comment = usercomment;     myLoadVars.send("collectNameAgeComment.pl","_self","GET"); } 

This is the basic strategy employed in collectNameAgeComment.fla on the CD. (The main difference is that collectNameAgeComment.fla uses TextInput components rather than text fields. Therefore, username , userage and usercomment become username.text , userage.text and usercomment.text .)

The first parameter of the send() method is the location of the CGI program. The second parameter is the target window, which will hold the results printed by the CGI program. In this case, "_self" indicates that the results should replace the current page, including the Flash movie. The third parameter is either a "GET" or a "POST" , depending on the method expected by the CGI program.

Suppose you don't want to replace the page and Flash movie with the results. Instead, suppose you want the Flash movie to continue. You would then use sendAndLoad() instead of send() . The sendAndLoad() method's second parameter is not a browser target, but another LoadVars object.

The initial LoadVars object holds the variables to be sent. The second LoadVars object contains the returned information. Here is an example:

 on (release) {     myLoadVars = new LoadVars();     myLoadVarsReceive = new LoadVars();     myLoadVars.id = userid;     myLoadVars.password = userpassword;     myLoadVars.onLoad = function() {         // do something with information here     }     myLoadVars.sendAndLoad("flashCollect.pl", myLoadVarsReceive, "GET"); } 

This approach is illustrated in flashCollect.fla and flashCollect.pl on the CD.

You can also use the POST method for sending variable values to the server. As a matter of fact, this approach is preferable because POST allows you to send long strings. The GET method limits string sizes depending on the browser and server.

With CGI.pm, the same Perl code retrieves both GET and POST information: You don't have to change a thing. However, in your Flash movie, you need to change load() , send() , or sendAndLoad() to use POST instead of GET .

Embedding Data on the HTML Page

Perhaps the most reliable and efficient way to send information from the server to your movie is to embed the information in the Web page in a place where your movie can get to it. You can do so by placing information in the src/movie parameters of both the OBJECT and EMBED tags on the Web page. For instance, a typical OBJECT movie parameter would look like this:

 <param name="movie" value="frompage.swf"> 

You also can place a question mark and a list of variable definitions after the name of the movie like this:

 <param name="movie" value="frompage.swf?var1=7&var2=42.8&var3=Hello!"> 

The result is that those three variables, starting with var1 , are set to their respective values. This happens immediately after the movie is loaded, so you can expect these values to be present when your scripts begin. All the variables will be at the root level.

Including Variables with loadMovie

The technique of placing variables after the movie filename also works in loadMovie() commands. You can tell your Flash movie to load a new movie in its place and include a question mark and then variable declarations. The new movie loads with these variables set. Here is an example:

loadMovie("mynewmovie.swf?a=7&b=42.8", this);


You also need to include the same information after the src parameter of the EMBED tag. Otherwise, only Windows users who have Internet Explorer will get the variables. The following is a complete OBJECT/EMBED tag with the variables set for both parts of the tag:

 <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/ shockwave/cabs/flash/swflash.cab#version=7,0,0,0" WIDTH="550" HEIGHT="400" id="frompage"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="frompage.swf?var1=7&var2=42.8&var3=Hello!" /> <param name="quality" value="high" /> <param name="bgcolor" value="#FFFFFF" /> <embed src="frompage.swf?var1=7&var2=42.8&var3=Hello!" quality="high" bgcolor="#ffffff" width="550" height="400" name="frompage" align="" type="application/x-shockwave-flash" pluginspace="http://www.macromedia.com/go/getflashplayer" /> </object> 

You can see this HTML page in action by using the Frompage.html and frompage.fla sample files. Run Frompage.html, which loads frompage.swf, which in turn reads and displays the variables from Frompage.html.

This technique is powerful even without any server-side support. For instance, you could make a Flash title movie for your Web site. Inside the movie, you could have a place to display the title of the page where the movie appears. This dynamic text field can be linked to a variable that is set on the Web page. So on one page, titleText could be My Home Page , and on another page titleText could be My Links . Both pages use the same Flash movie, but with a different value for titleText set in the src/movie parameters. You could run the same title movie on all your Web pages.

You could also send dynamic data to your movie by using this technique. A simple example is to send the current time to a movie. The Date object relies on the user's computer's time, which is usually set correctly but can easily be changed to anything. If you have a popular Web site, chances are good that people with incorrect dates and times will access your site every day. Even those site visitors with correct times may live in different time zones. What if you need to display the accurate date and time as it stands on your server?

You can display the correct time with a server-side include. A server-side include is a little tag that is put inside a Web page to add a bit of information, or a complete file, before it is sent to the user. The user gets a complete page that doesn't appear to be any different from a normal Web page, but the HTML on your site is specially coded so that the server knows what to include and where.

Server-Side Includes

Server-side includes are not turned on in all Web servers. Check with your server administrator or ISP to find out whether they are turned on, or whether there are any special settings required. For instance, many servers are set to not use server-side includes for .html files, but only for .shtml files.


To use server-side includes to send the time to Flash, you need to alter the src/movie parameter to look like this:

 timefrompage.swf?timeVar=<!--#echo var="DATE_LOCAL" -->& 

The server-side include is the <!--#echo var="DATE_LOCAL" -->& part. If the server is correctly parsing the file for server-side includes, it will see this and replace it with the date and time. The result might look similar to Sunday, 24-Feb-2002 10:18:19 MST .

When Double Quotes = Double Trouble

If the server-side include code is part of a block of text enclosed in double quotes, the double quotes around DATE_LOCAL may cause problems if the SSI doesn't work. On some Web servers, such as Apache, you can avoid this problem by using single quotes, like this:

 <PARAM NAME=movie VALUE="timefrompage.swf?timeVar=<!--#echo var='DATE_LOCAL' -->"> 

Unfortunately, in my testing on Microsoft IIS, the SSI did not work if I used single quotes. So you are stuck using double quotes on IIS. However, be aware that if you do use double quotes around DATE_LOCAL and the SSI doesn't work, the browser may become confused and not display the Flash file at all.


The server makes the change before sending the page to the user. If you view the page's source in the browser, you will see the actual date and time, and no hint that a server-side include tag actually appears there on the real HTML page.

The sample files timefrompage.shtml and timefrompage.fla do not work if you run them from your hard drive or the accompanying CD-ROM because you are not passing them through a Web server. Upload the .shtml and .swf files to a test directory on your site to see them in action. If you don't see a date and time in the dynamic text field in the movie but instead see the echo tag, you know that server-side includes have not been turned on.

Using server-side includes is probably the least sophisticated way to add dynamic information to your Web pages. Other systems are very popular now ”for example, Active Server Pages (ASP), JavaServer Pages (JSP), PHP, WebObjects, and ColdFusion. You could use any one of these examples to generate dynamic Web pages that include custom variables to be passed in to the Flash movie.

The main disadvantages of sending information to your movie with the src/movie tags are that the information typically needs to be short and that any user can see it if she simply views the source of the Web page she is visiting.



Using Macromedia Studio MX 2004
Special Edition Using Macromedia Studio MX 2004
ISBN: 0789730421
EAN: 2147483647
Year: N/A
Pages: 339

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