ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Actionscript to Server Comunication without Flex or a PHP daemon.
http://www.actionscript.org/resources/articles/1009/1/Actionscript-to-Server-Comunication-without-Flex-or-a-PHP-daemon/Page1.html
Joseph Tveter
PHP, JavaScript and ActionScript can be friends. The net seems short on information on how to do so. So I hope return what I have learned. 
By Joseph Tveter
Published on May 19, 2010
 
    You often want dynamic web pages or games embedded in them to communicate with the server to report scores, pull specific content, or simply log in. Here is one solution to server communication without Flex, or a PHP daemon listening for sockets. 

Passing Actionscript to Javascript to PHP to Javascript to Actionscript
     I banged my head into the wall searching for this information.  I found it fragmented all over. I thought I should give back what I have learned in my quest for Actionscript to server communication by putting it in one spot.  So here it is Passing Actionscript to JavaScript to PHP to JavaScript to Actionscript without Flex, and without a daemon listening for sockets. 

     I have included for download the files I used to build this example.  It is listed as Example.rar.  You may see it functioning Here. Although I slapped it together and does not function well.  You might need to hit the button a couple times to get it going.  But it was built in only 2 hours so its bound to have some bugs.  The Variable passing is sound, its the loaders that need a bit of a tweek.

     In this example we will have a page that will pull a list of images from a MySQL database to display in a slide show.  To do this example you will need, Flash, a PHP editor, a JavaScript editor, and a MySQL database.  You will also need a decent knowledge of Actionscript, JavaScript, PHP, and MySQL.  I say decent because I am an animator that has learned to script.  You don't need to be a scripting god to do this.  So forgive the imperfections this will not be as elegant as it could be.

     We want the web page to display a series of images, but we don't want excessive load times, and we only want some of the images from the total gallery.  To accomplish this task we will place the images for the slide show in a folder and create a database to hold the picture name, locations, and type.  Then we will establish our lines of communication. 

     PHP is run on the server before the page loads.  After the page is loaded PHP is NOT active unless you have a daemon running in the background. Because of the nature of PHP, ExternalInterface.call can not directly call functions within it.  PHP writes its information from the server, then publishes it to the client as a normal HTML document.  To call functions in PHP with ExternalInterface.call you must go through JavaScript and a form.

    






PHP and Server Communication
We will start with the PHP document.  Aside from the normal stuff, we will need to establish the form, database connection, and add the flash document.

The form will be our lines of communication.  We will set the form name to main, and put it on a loop to call the index page.  And a JavaScript function to activate the form that will be callable from Flash. 

[code]
<form name = 'Main' action='index.php' method='post'>
<input type='hidden' Name = 'Status' />
</form>

<script language="javascript">

//Function to expose the form to Flash.
function Submit(Status)
{
      document.Main.Status.value = Status;

      document.Main.submit();
}

//Function to expose $Status to Flash.
function GetStatus()
{
     Status = "<?php echo $Status; ?>";
     return Status;
}

//Function to check if Javascript is ready
function JSReady()
{
     Ready = true;
     return Ready;
}

<script language="javascript">
</script>
[/code]


In your PHP you should first establish the database connection.

[php]
$hostname='YourHostNameHere';
$username='exampleDB';
$password='Password123';
$dbname='exampleDB';

mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
[/php]


Once you have a database connection you should check to see if anything is being passed from the form.  Since this is the first load it will be null so we will set the $Status variable to 'Start'.

[php]
if(isset($_POST['Status']) and trim($_POST['Status']) != "" and trim($_POST['Status']) != "undefined" )
{
     $Status = trim($_POST['Status']);
}
else
{
         $Status = 'Start';
}
[/php]

Next we will establish the conditions of $Status and what they will do.  You could have it load the entire gallery but we are just going to start with nothing to show that nothing is up my sleeve.

But if $Status is 'Wedin' it will call GetGallery and pull all the wedding pictures. 
 
[php]
switch($Status)
{
     case Start:
     break;

     case Wedin:
          $WeddingArr = GetGallery('Wedding');

          //Array prep for JavaScript because you can not pass arrays from PHP but you can pass strings that can be turned into arrays.
          foreach ($WeddingArr as $key => $value)
          {
               if ($key < (count($WeddingArr)-1))
               {
                    $script = $script . "'" . $value . "',";
               }
               else
               {
                    $script = $script . "'" . $value . "'";
               }
          }

          //Now we build the Array in JavaScript and place it in a callable function.
 
          echo "
          <script language='javascript'>
               function GetWed()
               {
                    var Wed = [$script];

                    return Wed;
               }
          </script>
          ";

}


function GetGallery($AlbumName)
{
     //Establish The Record Count
     $cnt = 0;

     //Establish the query to the database and pull the result.
     $query = "SELECT * FROM photo WHERE AlbumName = '$AlbumName' ";
     $result = mysql_query($query) or die ('Could not execute');

     if($result)
     {
          //If there is a result build it into an array.
          while($row = mysql_fetch_array($result))
          {
               $returnMe[$cnt] = $row['folder'].$row['ImgName'];
               $cnt ++;
          }
     }
     return $returnMe;
}
[/php]

The last thing it needs is the actual flash movie.

[code]
<script language="javascript">
 
    // embed the flash movie
    AC_FL_RunContent(
      'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0',
      'width', '100%',
      'height', '100%',
      'src', 'mainstnav',
      'quality', 'best',
      'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
      'align', 'top',
      'play', 'true',
      'loop', 'true',
      'scale', 'noborder',
      'wmode', 'opaque',
      'devicefont', 'false',
      'id', 'mainstnav',
      'bgcolor', '#000000',
      'name', 'mainstnav',
      'menu', 'true',
      'allowScriptAccess','sameDomain',
      'allowFullScreen','false',
      'movie', 'mainstnav',
      'salign', 't'
      ); //end AC code

</script>
[/code]



Actionscript and Javascript

The foundation has been set.  We have a path from the database to a JavaScript function. Actionscript 3 has made calling JavaScript functions very easy but there are a few things to make ready before you can call.

Flash sometimes will load faster then JavaScript throwing an error if you call JavaScript before its done loading.  There are a couple ways around this but the one I prefer is to start a timer that will not let the program progress until JavaScript is loaded.

[as]
            var timer:Timer = new Timer(50, 0);

            timer.start();
            timer.addEventListener(TimerEvent.TIMER, JSReadyFun)
          
            function JSReadyFun(event:TimerEvent):void
            {
                JSReady = ExternalInterface.call("JSReady");
                EF.txt.appendText("JSReady-" + JSReady +"\n");
                if (JSReady == true)
                {
                    timer.stop();
                    EF.txt.appendText("Javascript Ready! \n");
                   
                    //When JavaScript is ready you can begin calling functions to display your dynamic content.

                    Status = ExternalInterface.call("GetStatus");
                    Status = Status.substr(0, 5);
                    Go();
                }
                else
                {
                    EF.txt.appendText("Javascript Not Ready. \n");
                }
            }
[/as]  

Here is the function in JavaScript that it is calling to see if it is ready.

[code]
//Function to check if Javascript is ready
function JSReady()
{
     Ready = true;
     return Ready;
}
[/code]

Once Flash is going the user can interact with it and use the javascript functions to query the database. The button is asking for all the wedding pictures by way of these functions.

[as]
function LoadPics(e:MouseEvent):void
            {
                //Excutes Form by way of javascript
                ExternalInterface.call("Submit", "Wedin");
            }
[/as]

The ExternalInterface.call to Submit in JavaScript executes the form Main.

[code]
function Submit(Status)
{
      document.Main.Status.value = Status;

      document.Main.submit();
}
[/code] 


Now the Page will reload with a form variable Status = 'Wedin'.  At the server the PHP captures the form data and places it in the string '$Status'.

[php]
if(isset($_POST['Status']) and trim($_POST['Status']) != "" and trim($_POST['Status']) != "undefined" )
{
     $Status = trim($_POST['Status']);
}
else
{
         $Status = 'Start';
}
[/php]

The switch on $Status executes the MySQL query in the GetGallery function.  You could save code by building the query data to a php string instead of an array, but i left it in just in case anyone wanted to see how to convert a php array to a JavaScript array.

[php]
switch($Status)
{
     case Start:
     break;

     case Wedin:
          $WeddingArr = GetGallery('Wedding');

          //Array prep for JavaScript because you can not pass arrays from PHP but you can pass strings that can be turned into arrays.
          foreach ($WeddingArr as $key => $value)
          {
               if ($key < (count($WeddingArr)-1))
               {
                    $script = $script . "'" . $value . "',";
               }
               else
               {
                    $script = $script . "'" . $value . "'";
               }
          }

          //Now we build the Array in JavaScript and place it in a callable function.

          echo "
          <script language='javascript'>
               function GetWed()
               {
                    var Wed = [$script];

                    return Wed;
               }
          </script>
          ";

}


function GetGallery($AlbumName)
{
     //Establish The Record Count
     $cnt = 0;

     //Establish the query to the database and pull the result.
     $query = "SELECT * FROM photo WHERE AlbumName = '$AlbumName' ";
     $result = mysql_query($query) or die ('Could not execute');

     if($result)
     {
          //If there is a result build it into an array.
          while($row = mysql_fetch_array($result))
          {
               $returnMe[$cnt] = $row['folder'].$row['ImgName'];
               $cnt ++;
          }
     }
     return $returnMe;
}
[/php]



Calling a function and retrieving an array is no differant then returning a string, int, or boolean.  Here is the capture of the array by Actionscript.

[as]
var WedPicList:Array = new Array;
WedPicList = ExternalInterface.call("GetWed");
[/as]

There and back again passing PHP to JavaScript to Actionscript to JavaScript to PHP.