Shockwave and PHP



This application uses the ActionScript sendAndLoad method of the LoadVars class to send data from a shockwave form to a PHP script and receive data from the script without the need to reload the page. This is now commonly referred to as AJAX but is perhaps better described as a partial page update.

Data returned from the PHP script is rendered into the shockwave using text boxes with properties set to be dynamic text.

You can get the Flash file directory.fla here.

The ActionScript is all in an event handler for the button.

on (release) {

   // check to make sure that there is input data
   if ( txtRequest.text != "" ) {

      // Prepare the data transfer objects
      var sender = new LoadVars();
      var receiver = new LoadVars();
      sender.request = txtRequest.text;

      // callback function to the receiver's onLoad event
      receiver.onLoad = function() {
         if ( this.name == "" ) {
            txtName.text = "no match";
         } else {
            txtName.text = this.name;
            txtRequest.text = "";
         }
         if ( this.phoneNumber == "" ) {    
            txtNumber.text = "no telephone number";
         } else {
            txtNumber.text = this.phoneNumber;
         }
         if ( this.email == "" ) {
            txtEmail.text = "no email address";
         } else {
            txtEmail.text = this.email;
         }
      }
      sender.sendAndLoad("http://stuweb.cms.gre.ac.uk/~mkg01/directory.php", receiver, "POST");
   }
}

directory.php

This PHP script connects to a MySQL database server and returns data as a single string containing name=value pairs separated by & delimiters.

Note that this script does not return an HTML document. Strictly speaking the header() function should be used to output the correct MIME type, although it is not entirely clear what that should be. The O'Reilly book 'ActionScript for Flash MX' makes insists that the output should be URL encode with a MIME type application/x-www-form-urlencoded but I find that this stops it from working.

<?php
if ( !isset($_POST['request']) || trim($_POST['request']) == "" )
    die('name=&phoneNumber=&email=');
$request = $_POST['request'];
require 'db.private';
$link = mysql_connect($host,$user,$passwd)
    or die('name=failed to connect&phoneNumber=&email=');
mysql_select_db($dbName,$link);
$query = "SELECT name, phone, email FROM directory WHERE name RLIKE '$request'";
$result = mysql_query($query,$link);
$row = mysql_fetch_row($result);
echo 'name=' . $row[0] . '&phoneNumber=' . $row[1] . '&email=' . $row[2];
?>

Have a look at this DHTML AJAX version of this application.