Advertisement

PASSING VARIABLES FROM HTML TO FLASH VIA QUERY STRING

 

OVERVIEW

 
 


This tutorial is very similar to another tutorial elsewhere on this site about Passing Variables From HTML to Flash via FlashVars.  The main difference is in the syntax; and it is fairly minor.  Also, FlashVars only works with Flash Player 6 (that is Flash MX) or newer.  If you're only supporting Flash Player 6 or newer, I recommend using FlashVars.

Note: ActionScript 3 user should go here after reding this tutorial for Action Script 3 way of accessing query strings.

Why and When to use Query String
Flash supports several methods of communicating to the outside world.   Some of the common methods are: loadVariables, the XML object, the FlashVars, and the XMLSocket.  With these methods, you can retrieve parameters via an external file or via CGI scripts.   However, there is a less conventional method, which is to use what is called the query string.  This method is practical but only suitable for simple situations such as these:  

  • The data to be passed is fairly simple.  By simple, I mean simple text (such as user name, filename, id, or cookie info).
  • The data to be passed is not long.  I recommend less than 1024 characters.  (The actual limit  depends on the browser and the server.)
  • You don't care about the security of the data.  
    Query string is not secure.  Any user can easily see the content of the query string in the browser's URL/Address bar; or by viewing the page source (as will be shown later).  Something like a password should NEVER be passed via the query string.  Let me say this again: anything even remotely sensitive should not be passed via the query string.   

What is Query String?
Query string is the string that follows the "?" sign within an URL.  Below, is an URL followed by the query string.

The query string by itself (such as shown above) normally is not very meaningful to the end user.  Most commonly, query string is used by CGI programs to retrieve data from HTML forms.   As an example, in the above case, suppose that the file mycgi.pl is a CGI program, it will be able to retrieve these variable and value pairs from the query string:

  • message = hello
  • day = Tuesday

Advertisement
FastClick Ad Network
 

Side note: Doing a search on Yahoo for the word "Flash" yields this query string:

Here' you can see that the query string is as follows:

p=flash&ei=UTF-8&fr=fp-tab-web-t&cop=mss&tab=

This is an example of how the form data is sent to the search engine via the query string.   You, the user, don't usually care how the query string works (the query string may even look like a gibberish).  You may not even notice that it is there in the URL.  The CGI program handles the details for you.  

Basic Query String Syntax
The format of the query string is as follows:

variableName1=variableValue1&variableName2=variableValue2&variableName3=variableValue3...

Each variable name and value pair is separated by a '=' sign; and an '&' sign separates the variables.  You can have as many variable name and value pairs, but remember, there is a limit, and I recommend not more than 1024 characters total (including the www... URL part).  After all, if you need more space, you should consider using other methods, such as reading from a data file.  

Several more things that should be noted: 

  • You can add (type) a query string manually to an URL.  For example, I can enter http://www.permadi.com/index.html?message=Hello, and the page will work as usual.  The query string is simply ignored if the destination URL doesn't do anything with it.   (index.html file in the above example does not do anything with the query string, so it's simply ignored).  This is something that doesn't seem useful, but  later you will see how it can be utilized.  
  • Do not put line breaks within a query string. even if the string is long.

Several things that should be noted about variable names: 

  • Use only letters, underline, and numbers.  Avoid symbols such as '$' or '#'.  
  • Do not start a name with a number (1message is an invalid variable name because the name starts with a number; whereas message1 is a valid variable name).  
    Flash will certainly reject or get confused if you use a variable name that starts with a number or other special characters - except underlines (ie: _message, and _1message are valid names). 
  • A variable name should not contain any <space> character (ie: my message is an invalid name, my_message is a valid name).  

And for variable values, there are also rules:

  • Characters needs to be URL encoded (see: Introduction to URL Encoding).  This means that special characters, such as =, &, <SPACE>, + need to be substituted with their URL encoded format.  For example: name=John Doe.  Here, the <space> between John and Doe needs to be encoded with + sign, so you need to pass it as name=John+Doe or name=John%20Doe.  (Flash doesn't seem to enforce this, but you should follow the proper way.)  Search for URL encoding on the net for more details on this subject.  
  • If you need to include an & as part of a value, such as in ingredients=Beef&Pork, then you need to encode the & like this: ingredients=Beef%26Pork.   The %26 is an encoded form of the & sign.  The number 26 is the hexadecimal code of the character &.  If you need to know the encoding value of a particular character, consult an ASCII table.  There are other characters that need to be encoded, such as <, >, /, ?.  
 

QUERY STRING AND FLASH

 
 
  
Now that we know what a query string is, let's see how it applies to Flash.   

When you put a Flash movie on a html page, you will have an OBJECT tag code that is similar to this: 

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=4,0,0,0"   
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie VALUE="flaMovie.swf">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie.swf" bgcolor=#99CC33 WIDTH=250 HEIGHT=250 
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

In that example, the Flash movie filename is: flaMovie.swf.  Notice how that filename is used twice; this is the result of incompatibilities between Netscape and Internet Explorer.  To be on the safe side, you should support/use both.  

You can append a query string following the Flash movie filename, and Flash will get the variable(s) from the query string for you automatically.  The variable(s) will go into the _root or _level0 of the movie.   Note: ActionScript 3 user should go here after reding this tutorial for Action Script 3 way of accessing query strings.

Let's see some examples.
  

 
 

EXAMPLE 1
Using Query String to Maximize Code Reuse

 
 

  
In this contrived example, suppose that you have a Flash movie that loads an image file and display the image (using loadMovie on Flash MX - if you're using Flash 5, think of it as loading another .swf file).  

You want to be able to use the same swf file on many pages to show different images.  Obviously, you need to pass the image filename to Flash.  What can you do?  Since a filename is such a simple text, you can use query string to pass it.  

Assuming the image filename is image1.jpg, located at a folder named images.  And assuming that the Flash movie will use a variable named imageFilename to refer to the file, then we can do this:

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://download.macromedia.com/"  
  WIDTH="250" HEIGHT="300" id="flaMovie1">
  <PARAM NAME=movie VALUE="flaMovie1.swf?imageFilename=images%2Fimage1%2Ejpg"> 
  <PARAM NAME=quality VALUE=high>
  <PARAM NAME=bgcolor VALUE=#FFFFFF> 
  <EMBED src="flaMovie1.swf?imageFilename=images%2Fimage1%2Ejpg" 
    quality=high bgcolor=#FFFFFF WIDTH="250" HEIGHT="250" NAME="flaMovie1"
    TYPE="application/x-shockwave-flash" 
    PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
  </EMBED>
</OBJECT>

There you see that I appended a query string after the Flash movie filename (flaMovie1.swf).  The query string contains one variable: imageFilename, with the value of images/image1.jpg.  

Note: The %2F is the url encoding for the "/" sign, and %2E is the url encoding for the "." sign.  Since these symbols are unsafe or reserved, we should url encode them, although at the present Flash does not seem to care.  So saying: imageFilename=images%2Fimage1%2Ejpg is essentially the same as saying imageFilename=images/image1.jpg (see: Introduction to URL Encoding)

In this way, when the Flash movie starts, that movie will have a variable named imageFilename within its _root or _level0.  Then, I can say: loadMovie(_root.imageFilename); and it will load the specified image.  

Note: ActionScript 3 user should go here after reding this tutorial for Action Script 3 way of accessing query strings.

Here are example of the swf file with different query string being passed:

 imageFilename=images/image1.jpg

imageFilename=images/image2.jpg

 Advertisement
FastClick Ad Network

 
 

EXAMPLE 2
Passing Cookie to Query String

 

  
Suppose that you have a Flash movie that displays the current user name; and the user name is stored in a cookie.  You can get a cookie value into Flash via loadVariables (with CGI); or even using JavaScript and FSCommand (see here).  But, since the userName is a fairly simple data, let's see how it can be done with a query string.  Note: Query string is not safe, user can see it.  Anything confidential like a password should NEVER be passed via the query string.

Because you don't even know who the user will be, you cannot hard code the query string.   That is, you cannot put: flashMovie.swf?userName=jim2000 in the html code since userName might be jane2 instead of jim2000.   So, in this case, we must use another way to get the proper query string value.  This requires being able to write the query string on the fly, as will be explored later.   Let's first create a cookie.  Enter a user name below then click the button.   When the button is clicked, a cookie named "userName" will be created for you (JavaScript must be enabled for this example to work): 

Please enter userName  

Now that we have a cookie, let's see how we can get the cookie into Flash.  Because Flash does not support cookie reading directly, we need to use a scripting language.   I will show 2 examples.  The first one uses ASP, the second one uses JavaScript, and the third one uses PHP.  

Using ASP

Below is an example of using ASP to get the cookie value and pass the value to Flash.  

<HTML>
<HEAD><TITLE>Example</TITLE>
<BODY>
<%
'compose OBJECT string
swfTag = _
  "<OBJECT classid=""clsid:553540000"""& vbCrLf & _
  " codebase=""http://macromedia.com/rsion=4,0,0,0"""& vbCrLf & _
  " ID=flaMovie WIDTH=250 HEIGHT=75>"& vbCrLf & _
  " <PARAM NAME=movie "& vbCrLf & _
  " VALUE=""flaMovie2.swf?userName=" & _
   Server.URLEncode(Request.Cookies("userName")) &""">"& vbCrLf & _
  " <PARAM NAME=quality VALUE=medium>"& vbCrLf & _
  " <PARAM NAME=bgcolor VALUE=#99CC33>"& vbCrLf & _
  " <EMBED src=""flaMovie2.swf?userName=" & _
   Server.URLEncode(Request.Cookies("userName")) &""""& vbCrLf & _
  " bgcolor=#99CC33 WIDTH=250 HEIGHT=75 "& vbCrLf & _
  " TYPE=""application/x-shockwave-flash"">"& vbCrLf & _
  " </EMBED>"& vbCrLf & _
  "</OBJECT>"
 'writes out the OBJECT string
 Response.Write swfTag
%>
</BODY>
</HTML>

Notice that I added lots of carriage returns (vbCrLf) so that the resulting code will be easier to debug.  (Ie: when you open the page and view the page source, this prevents having everything written on a single line.).  The 

When that code is run, the line 

  " VALUE=""flaMovie2.swf?userName=" & _
   Server.URLEncode(Request.Cookies("userName")) &""">"& vbCrLf & _

will be replaced with something like flaMovie2.swf?userName=john, assuming john is the userName stored in the cookieThe Server.URLEncode() function will make sure that the string is URL encoded, otherwise, if you enter something like "Jack & Joan", Flash will not interpret it correctly because the "&" sign is a special character.

Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)

You can do it more cleanly and efficiently with a code like below (even better, you should consider writing a function if you use the code often):

<HTML>
<HEAD><TITLE>Example</TITLE></HEAD>
<BODY>
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=4,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=75>
  <PARAM NAME=movie 
    VALUE="flaMovie2.swf?userName=<%=Server.URLEncode(Request.Cookies("userName"))%>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie2.swf?userName=<%=Server.URLEncode(Request.Cookies("userName"))%>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250 
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>
</BODY>
</HTML>

 
Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)

Using JavaScript

With JavaScript, the process is similar.  You can use document.write to pass the query string to Flash.  You will need to write the entire OBJECT tag, since JavaScript is a client side scripting language, and you can't run a JavaScript code nested within an OBJECT tag.  An example is shown below.  

<HTML>
<HEAD><TITLE>Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
// a simple function that returns the value of a cookie
function getCookie(name)
{
  if (document.cookie)
  {
    var cookies=document.cookie.split(";");
    for (var i=0; i<cookies.length; i++)
    {
      var varName=(cookies[i].split("=")[0]);
      var varValue=(cookies[i].split("=")[1]);

      // the next 2 lines trim whitespaces (Netscape 7 problem)
      while (varName.charAt(0)==" ")
        varName=varName.substr(1,varName.length);
      // the escape() function will return URL encoded string.
      if (varName==name)
        return escape(varValue);
    }
  }
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
// this writes out the entire OBJECT tag.  If you use this kind of code
// often, you should consider writing a function to do this.  Then you
// can pass parameters (swf filename, width, height, etc) and reuse the
// function.  Some parameters have been truncated to fit this space.  
// Just pay attention to the red portion.
document.write(
  '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\n'+
  '  codebase="http://macromedia.com/cabs/swflash.cab#version=4,0,0,0"\n'+   
  '  ID=flaMovie WIDTH=250 HEIGHT=75>\n'+
  '  <PARAM NAME=movie '+
  '    VALUE="flaMovie2.swf?userName=' + getCookie('userName')+'">\n'+
  '  <PARAM NAME=quality VALUE=medium>\n'+
  '  <PARAM NAME=bgcolor VALUE=#99CC33>\n'+
  '  <EMBED src="flaMovie2.swf?userName=' + getCookie('userName')+'">\n'+
  '    bgcolor=#99CC33 WIDTH=250 HEIGHT=250 \n'+
  '    TYPE="application/x-shockwave-flash">\n'+
  '  </EMBED>\n'+
  '</OBJECT>\n');
//-->
</SCRIPT>
</BODY>
</HTML>

Note: Coding document.writes like above is very error prone and hard to debug because when you do View Source after opening the document, you don't see what the being written by the document.writes.  Sometimes you forget to put a closing tag or a closing ">" and don't know why the page won't load.  The easiest way for me to debug this kind of code is to use an older Netscape 4.8 browser.  That older browser (at least the PC version) shows the result of document.writes when you do View Source.  This is also why I appended the \n (start anew new line) often: to make it easier to see the result.

Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined).  Note: The escape() function in getCookie() will make sure that the string is URL encoded, otherwise, if you enter something like "Jack & Joan", Flash will not interpret it correctly because "&" is a special character.  Note however, that the escape() function does not encode '+' and '/' characters.  For a workaround, see here.

Using PHP
  
This example is for PHP 4 or above.

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie VALUE="flaMovie2.swf?<?php echo(urlencode($userName));?>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED src="flaMovie2.swf?userName=<?php echo(urlencode($userName));?>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250 
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

Or, using $HTTP_COOKIE_VARS[]:

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  codebase="http://macromedia.com/cabs/swflash.cab#version=6,0,0,0"
  ID=flaMovie WIDTH=250 HEIGHT=250>
  <PARAM NAME=movie 
    VALUE="flaMovie2.swf?<?php echo(urlencode($HTTP_COOKIE_VARS["userName"]));?>">
  <PARAM NAME=quality VALUE=medium>
  <PARAM NAME=bgcolor VALUE=#99CC33>
  <EMBED 
    src="flaMovie2.swf?userName=<?php echo(urlencode($HTTP_COOKIE_VARS["userName"]));?>"
    bgcolor=#99CC33 WIDTH=250 HEIGHT=250 
    TYPE="application/x-shockwave-flash">
  </EMBED>
</OBJECT>

When that code is run, the line $userName (which is the same as $HTTP_COOKIE_VARS["userName"]) will be replaced with the userName stored in the cookieThe urlencode() function encodes the string to make sure that special characters in the string are URL encoded.  Without this, if the userName contains special characters, such as the "&" character in: John & Associates, then the result will become unpredictable.

Click here to see the page generated by the script above.  (Remember to set the cookie first using the form above, or the result will be undefined)

Next, we will discuss how to pass HTTP query string (such as data from html forms) to Flash. 

<<NEXT PAGE>>
<<
INDEX>>

Terms of Use
permadi@permadi.com
 
(C) F. Permadi