devxlogo

Four Ways to Transfer Data Between Flash and PHP

Four Ways to Transfer Data Between Flash and PHP

hen you need to develop a web form with a special design and great effects, you will probably elect to use Flash. But building and programming Flash forms is considerably different from building standard HTML-based forms. You program Flash using its proprietary (but JavaScript-like) ActionScript language—which is great if you’re already a Flash developer—but as a PHP developer it’s is more desirable to implement the business logic in PHP and use the Flash form simply to gather the data. To do that though, you need to know how to access data in the Flash form and (sometimes) how to update the Flash form from PHP as well. That’s exactly what you will see how to accomplish in this article.

Creating the Flash Form
As an example, take a look at the Flash form in Figure 1. You’ll see how to create, and communicate with, the form. To get started:

 
Figure 1. Sample Flash Form: The Flash form used in this article provides a test bed for bidirectional communications between Flash and PHP.
  1. Open Macromedia Flash, and choose the “New” option from the File menu.
  2. From the New Document window, General tab, choose the “Flash Document” option, and then click OK.
  3. From the Insert menu, choose the New Symbol option to create a new movie clip.
  4. Rename the movie clip flashForm, and click OK.
  5. Use the Rectangle Tool from the Tools menu to draw a rectangle of 561×493 pixels on the flashForm surface, and set the background color to #CCCCCC.
  6. Next, use the items from the Components panel (UI Components node) to reproduce the form design from Figure 1.
  7. Use the Properties panel to reproduce the component properties you can see in Figure 1 (the red arrows);
  8. Save your project as flashForm.fla.

With the Flash form created, you can move to the next task—communicating with the form.

Preparing Flash Data
Although your primary business logic will be in PHP, you can’t avoid ActionScript altogether; you need to write a little ActionScript code to retrieve and prepare the data to be sent to PHP. That means you need to know how to extract the data for each type of Flash component (just as in JavaScript, the code you use to get data from a control depends on the control type). For the various controls, here’s the ActionScript you’ll need:

  • For TextInput components, use the text property. For example, you can extract data entered into the name and email TextInput components with the following code:
       _parent.name.text   _parent.email.text
  • For RadioButton components, use the selection property, which returns the selected radio button from the group. In this case, you want the button’s label, so you can use:
       _parent.radioGroup.selection.label
  • For ComboBox components, use the value property, which returns the selected item. Here’s the code to determine the selected country from the dropdown country list:
          _parent.country.value

    Note: Code such as the preceding examples belongs in the Actions panel of the Submit button, so it will run when users click Submit.

  • CheckBox components are a little more complicated. You need to create a global array to store the labels of the selected Newsletter checkboxes and a global function that checks whether a selected checkbox label is already in the global array. If the label is found, then the function returns the position (index array) where it was found; otherwise, it returns -1. Here’s the ActionScript to perform the check:
       onClipEvent(load)   {      _global.checkboxArray = new Array();         _global.testIfSelected = function (t)       {         for(i=0;i
    Author's Note: Place the preceding function in the Actions panel of the movie clip (this panel is available only after you drag an instance of the flashForm movie clip on the scene).

    To avoid adding a checkbox label to the array multiple times, you'll need to call the testIfSelected function every time a user selects or deselects one of the checkboxes. Therefore, each checkbox control implements the following action:

    Author's Note: Place the following code in the Actions panel of every checkbox.

       on (click) {      var pos=testIfSelected(this.label);         if(this.selected == true)      {               if(pos == -1) checkboxArray.push(this.label);      }       else       {         if(pos >=0) checkboxArray.splice(pos,1);      }   }
    Author's Notes:
    • To view the Actions panel of a Flash component, left-click the component and expand its Actions panel.
    • To see the flashForm movie clip, press Ctrl+L, which opens the Library panel, and then double-click the flashForm name.

    Finally, when a user submits the form you can join the labels of the selected checkboxes into a comma-delimited string using the join method, like this:

       checkboxArray.join(",")
    Author's Note: Put the preceding code line and the rest of the code in this section in the Actions panel of the Submit button.

  • List components are similar. Because the list used in the example supports multiple selections you have to determine and submit all the selected articles. The following code concatenates the article labels into a comma-delimited string:
       var listSelection = new Array();   var listLabels = "";   listSelection = _parent.format.selectedItems;   for(j = 0; j 
  • TextArea components hold multiple lines of text, but you retrieve it with the text property just like a TextInput control:
       _parent.observation.text
  • Now that you know the basics of how to collect the needed data from the Flash controls, you can move forward with sending that data to PHP.

    Flash to PHP Using getURL()
    Although Flash offers additional techniques for sharing data with server languages such as PHP, Java, ColdFusion, ASP, and so on, this article covers only the most commonly-used techniques: the getURL method and the LoadVars class. To get data to PHP using ActionScript, you can call the getURL method, which loads a page into the browser from a specified URL. The syntax of getURL is:

   getURL(url [, window [, "variables"]])

The parameters to getURL are:

  • url—the URL to load.
  • window—The window to accept any response from the server, which can be _self (default), _blank, _parent, or _top.
  • variables—A string that specifies the HTTP method to use: either GET or POST.

For example, to send the data from the sample form you can call getURL like this:

   on (release)   {            var request="form.php" +          "?username="+_parent.name.text+         "&useremail="+_parent.email.text+         "&usersex="+_parent.radioGroup.selection.label+         "&usercountry="+_parent.country.value;               var selectedCheckboxes=checkboxArray.join(",");      var listSelection = new Array();      var listLabels = "";      listSelection = _parent.format.selectedItems;      for(j = 0; j
Author's Note: The preceding code goes in the Actions panel of the Submit button.

The other common technique for sending data from Flash to PHP uses the LoadVars class, an ActionScript class that exposes three methods for loading and sending data to a server language: load, send, and sendAndLoad.

The send method syntax is:

   lv_object.send(url [,target, method])

In the preceding code, the lv object is an instance of the LoadVars class. The parameters to the send method are:

  • url—the URL that receives the data
  • target—the window target to accept any answer from the server, which can be _self (default), _blank, _parent, or _top.
  • method— A string that specifies the HTTP method to use: either GET or POST.

For this example, you want to call the send method when a user clicks the Submit button, by placing the following code in the Submit button's Actions panel:

      on (release)   {            var selectedCheckboxes=checkboxArray.join(",");      var listSelection = new Array();      var listLabels = "";      listSelection = _parent.format.selectedItems;      for(j = 0; j

Receiving Flash Data in PHP
At this point, when you click the Submit button, the form delivers the data to a PHP page on the server. Now you need to write the logic. The page form.php (available in the downloadable sample code) extracts the GET (or POST) data from Flash and implements the business logic. For the purposes of this example, it simply returns an HTML table that contains the data received, as proof that the PHP script was able to access the data sent by the Flash form:

      form.php        
Variable Name Variable Value
username
useremail
usersex
usercountry
checkboxes
list
observation

You've seen two techniques for moving data from Flash to PHP. Next, you'll see how to send data from PHP to Flash.

From PHP to Flash Using LoadVars
Getting Flash data to PHP is fine if you need to display only blank forms, but for most purposes, you also need to be able to set control values in the Flash form from PHP as well. To send data from PHP to Flash you can use the LoadVars.load method. This method detects when a Flash form receives data from an external program. When all the data has been transferred, Flash calls the LoadVars.onLoad method, which represents the success of the transfer using a Boolean value. The syntax of the load method is:

   lv_object.load(url)

In the preceding code, the lv_object is an instance of the LoadVars class, while url is the URL from which Flash should download the variable values.

For sending data to Flash you can use the echo/print PHP methods. For each data item use the following syntax:

   &flash_variable_name=$php_variable_name;

For example, to send a message to flashForm from form.php add the following code at the end of the script:

   

To receive the message in flashForm place this code in the Actions panel of the Submit button, at the end of the on(release) method:

   myData = new LoadVars();   myData.load("form.php");   myData.onLoad = function(success)     {        if(success)        {           _parent.messageFromPHP.text =              myData.varMessageFromPHP;        }     }
 
Figure 2. PHP Message: The sample Flash form displays messages from PHP in a label control.

Figure 2 shows flashForm displaying the message from PHP in a Label component:

Reading Data from a Text File
Another option for sending data from PHP to Flash is to use a text file as an intermediate data buffer. For example, the following PHP code (fileForFlash.php) generates a text file (data.txt) that contains a set of values to pre-populate the flashForm form. After the stream is closed, PHP loads the flashForm form. Notice how you should generate the file so that Flash can parse it correctly:

   ';   echo '';   echo '';   echo '';   echo '';   echo '';   echo '';      ?>

Now you can load the values from the file into PHP using the LoadVars.load method like this (the form is pre-populated when Flash loads the Submit component, because you are using the load event, which takes effect when the form's components are loaded):

   on(load)   {            myData = new LoadVars();      myData.load("data.txt");        myData.onLoad = function(success){      if(success)      {         //"name" text field         _parent.name.text = myData.username;         //"email" text field         _parent.email.text = myData.useremail;         //"male"/"female" radio buttons         if(myData.usersex == "Male")         {            _parent.male.selected = true;            }          else          {             _parent.female.selected = true;          }         //"country" combobox          for(l=0;l<_parent.country.length if _parent.country.selectedindex="l;" _parent.country.dispatchevent target:_parent.country break .. checkboxes var checkboxes:string="(myData.checkboxes).toString();" _parent.checkbox1.selected="true;" _parent.checkbox2.selected="true;" _parent.checkbox3.selected="true;" _parent.checkbox4.selected="true;" list for _parent.format.selectedindex="l;" text area _parent.observation.text="myData.observation;" from php _parent.messagefromphp.text="myData.message;">
Author's Note: Paste the preceding on(load) method code in the Actions panel of the Submit button. The on(load) method runs when the Submit component gets loaded. Don't overwrite the on(release) method shown earlier.

 
Figure 3. Pre-Populated Form: Here's the sample Flash form pre-loaded with data from the data.txt file created on the server with PHP.

Figure 3 shows the sample form loaded with the data from the data.txt file.

What's in the Sample Code?
You'll find four zip files in the downloadable sample code that implement the techniques discussed in this article.

  • Example1.zip sends data from Flash to PHP using the getURL method.
  • Example2.zip sends data from Flash to PHP using the LoadVars.send method.
  • Example3.zip sends data from PHP to Flash using the LoadVars.load method.
  • Example4.zip pre-populates the Flash form using an intermediate text file generated by a PHP page. When the application submits the pre-populated values they are sent to another PHP page.

All in all, using Flash and PHP together can be a great solution when you need to combine special designs/effects with strong business logic in professional web applications. Now that you've seen how to transfer data between the two different technologies, you can add Flash-based forms to your PHP applications and make them work together smoothly.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist