Examples

Falcon - Adobe Flash 9 AS3 Server Script Connection Class

Below is the sample code that comes with the Falcon ZIP file of examples and instructions.

VARIABLES EXAMPLE (AS)

package falcon{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.text.TextField;
	public class FalconVariables extends MovieClip {
		public function FalconVariables() {
			var myFalcon:Falcon=new Falcon("http://www.yoursite.com/yourscript.php");
			myFalcon.addEventListener(Event.COMPLETE,getData);
		}
		private function getData(e:Event) {
			if (e.target.error) {
				myText.text = "sorry, error connecting to server script";
			} else {
				myText.text = e.target.data.yourVariable; // will say Hello...
			}
		}
	}
}

VARIABLES EXAMPLE (PHP)

<?PHP
	echo "yourVariable=Hello from the server";
?>

TEXT EXAMPLE (AS)

package falcon{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.text.TextField;
	public class FalconText extends MovieClip {
		public function FalconText() {
			var myFalcon:Falcon=new Falcon("sample.txt", Falcon.TEXT);
			myFalcon.addEventListener(Event.COMPLETE,getData);
		}
		private function getData(e:Event) {
			if (e.target.error) {
				myText.text = "sorry, error accessing text file";
			} else {
				myText.text = e.target.data;
			}
		}
	}
}

TEXT EXAMPLE (TXT)

Hello from a text file

How are you?

XML EXAMPLE (AS)

package falcon{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.text.TextField;
	public class FalconXML extends MovieClip {
		public function FalconXML() {
			var myFalcon:Falcon=new Falcon("sample.xml", Falcon.XML_DATA);
			myFalcon.addEventListener(Event.COMPLETE,getData);
		}
		private function getData(e:Event) {
			if (e.target.error) {
				myText.text = "sorry, error connecting to XML file";
			} else {
				myText.text = e.target.data.text; 
				myText.appendText("\n\n"); // new lines
				myText.appendText(e.target.data.author);
				myText.appendText("\n"); 
				myText.appendText(e.target.data.location.@city);
				myText.appendText(", "); 
				myText.appendText(e.target.data.location.@country);
			}
		}
	}
}

XML EXAMPLE (XML)

<?xml version="1.0" encoding="utf-8"?>
<sample>
	<text><![CDATA[Hello there from <XML>]]></text>
	<author>Dan Zen</author>
	<location country="Canada" city="Dundas" />
</sample>

DATA PROVIDER EXAMPLE (AS)

package falcon{
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.text.TextField;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import fl.data.DataProvider;
	public class FalconDataProvider extends MovieClip {
		// this code uses the FalconProvider class to send and load variables
		// FalconProvider is a class that wraps the half dozen Flash data classes
		// FalconProvider also creates a dataProvider for sequenced data (name1, name2, name3, etc.)
		private var myFalcon:FalconProvider;
		private var myScriptURL:String = "http://www.yourserver.com/yourscript.php";
		private var myDataType:String = FalconProvider.VARIABLES;
		private var mySendVars:Object = new Object; // object for sending variables
		public function FalconDataProvider() {
			getData();
			mySubmit.addEventListener(MouseEvent.CLICK, submitData);
		}
		function getData(myFirstName:String="", myLastName:String="", myFear:String="") {
			// preparing data to send to the server script
			mySendVars.firstName = myFirstName;
			mySendVars.lastName = myLastName;
			mySendVars.fear = myFear;

			// here we create a Falcon Object to send and receive data from the server script
			myFalcon = new FalconProvider(myScriptURL, myDataType, mySendVars);
			myFalcon.addEventListener(Event.COMPLETE, showGrid);
		}
		private function showGrid(e:Event) {
			if (e.target.error) {
				trace("there was an error connecting to the server");
			} else if (e.target.data.error != 0) {// (optional) we are sending a error check from the server script
				trace(e.target.data.error);
			} else {
				// if variables are sent with number iterators like:
				// name1, age1, name2, age2, etc. (or name0, age0, name1, age1, etc.)
				// then these are put in e.target.dataProvider as name, age, etc.
				// this allows you to populate DataGrid objects as below
				// or populate List and ComboBox objects using label1, data1, label2, data2, etc.
				myGrid.columns = ["firstName", "lastName", "fear"];
				myGrid.dataProvider = e.target.dataProvider;
				myGrid.getColumnAt(0).headerText = "First Name";
				myGrid.getColumnAt(0).width = 90;
				myGrid.getColumnAt(1).headerText = "Last Name";
				myGrid.getColumnAt(1).width = 90;
				myGrid.getColumnAt(2).headerText = "Greatest Fear";
			}
		}
		function submitData(e:MouseEvent) {
			if (firstName.text == "" || lastName.text == "" || fear.text == "") {
				navigateToURL(new URLRequest("javascript:alert('Please enter all fields');"), "_self");
			} else {
				getData(firstName.text, lastName.text, fear.text);
				firstName.text = lastName.text = fear.text = "";
			}
		}
	}
}

DATA PROVIDER EXAMPLE (PHP)

<?php
	$firstName = isset($_POST['firstName']) ? $_POST['firstName'] : "";
	$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : "";
	$fear = isset($_POST['fear']) ? $_POST['fear'] : "";

	$date = date("Y-m-d");
	$error = 0;

	// PRE-MAKE DATABASE
	// go to phpmyadmin
	// login and make a table called "fears" with 5 fields
	// id - make it an INT and autoincrementing and the key
	// firstName - make TEXT
	// lastName - make TEXT
	// fear - make TEXT
	// date - male Date

	// OPEN DATABASE
	// use your username and password
	$db = mysql_connect("localhost", "yourUsername", "yourPassword");
	mysql_select_db("yourDatabase",$db);
	
	if ($firstName != "") {
		// INPUT TO MYSQL
		// create SQL query to insert any names and fears into the "fears" table
		$query = "INSERT INTO fears (id, firstName, lastName, fear, date) VALUES ('', '$firstName', '$lastName', '$fear', '$date')";
		// use PHP function to execute query.  We use this function every time we
		// want to access the database - for instance to add, delete or change something
		$result = mysql_query($query,$db);
		if (!$result) {
			$error = "Sorry could not record fear";
		}		
	}	
	
	// OUTPUT TO FLASH
	// this is how we handle sending variables back to Flash
	// note that all name=value pairs are separated by &
	$query = "SELECT * FROM fears";
	$result = mysql_query($query,$db);
	$total = mysql_num_rows($result);
	$output = "";
	if ($result) {
		$i=0;
		while ($myrow = mysql_fetch_array($result)) {
			$i++;
			$output .= "&firstName".$i."=".urlencode($myrow['firstName']).
				   "&lastName".$i."=".urlencode($myrow['lastName']).
				   "&fear".$i."=".urlencode($myrow['fear']);
		}
	} else {
		$error = "Sorry could not access fears";
	}

	// send the data to Flash using the URL encoded format
	echo "total=".urlencode($total)."&error=".urlencode($error).$output;
?>

31 Responses

  1. Hi
    I love the concept, but I have trouble getting anything to work, other than the text file example.
    The XML example, loads the sample file, but cannot parse it and leaves these errors in the output section:
    —————–
    ReferenceError: Error #1069: Property text not found on String and there is no default value.
    at falcon::FalconXML/getData()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at Falcon/getData()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()
    ————–
    Any ideas?
    Regards

  2. Thanks RL

    Oops – we posted an older version of the XML sample for some reason. The way we passed in parameters changed order and so it was thinking the result coming back was text as opposed to XML. The current ZIP file has the changes.

  3. great examplesssss keep it up

  4. Hi

    Looks like it would be great but I don’t understand anything here! Your examples on the website just display the code in the examples you provide in the zip file, not showing how to actually connect it to the swf. I keep getting the same error as RL with the reference error and this is with the example you provide! Can you please clarify this?

  5. Thanks Chris… you were right and we have updated the code again! Sorry about that. Blame Microsoft for providing an overwrite warning that comes 10 seconds after you try and delete a folder with one of its sub folders open! What the heck are they waiting for and why even give an error?! So the XML example will work now – make sure you clear your cache…

    If you look in the readme, it gives a summary of how the classes connect to the Flash file for those who have not used classes so have a read there.

    A synopsis is that each FLA file can have a document class (an external ActionScript file) associated with it through the properties panel when you click on the stage. This class (a bunch of code in a specific format) is what calls Falcon or FalconProvider. Sample FLA and their document classes are provided. When you CTRL Enter or Apple Return Flash compiles the FLA and the code from all classes used into the SWF.

  6. Thank you!!

    I thought I was going crazy!! I’m new to AS 3 and Flash CS3, coming from Flash MX I’ve had a very steep learning curve in a very short period of time. I wasn’t sure if it was just me missing something or the code. Examples work beautifully now.

    Thanks for the quick response and for helping me out!

  7. Just had difficulty with XML that has namespaces for instance itunes use namespaces and other feeds like Time Text cue point XML where you will see parameters such as xmlns="http://www.w3.org/2006/04/ttaf1" and xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling".

    This can mess up how you read the XML – it is not a Falcon issue. To access data in the namespaces you can define the namespace in Flash

    var mySpace:Namespace = new Namespace("tts");

    // or

    var mySpace:Namespace = new Namespace("http://www.w3.org/2006/04/ttaf1");

    Then assuming your XML is stored in a variable called myXML, you can access elements like myXML.mySpace::someTag if the tag is prefixed with the namespace in the xml like tts:someTag. (attributes can be prefixed too).

    But if you want to gain access to tags that are not prefixed with the the namespace then you can put this line before you try and access your tags:

    default xml namespace = myXML.namespace();

    I think that will work in most cases – you would think that it would work automatically but it did not seem to. Once you are finished parsing your XML you should set the default namespace back to null otherwise it turns out that your events don’t work ;-)

    default xml namespace = null;

  8. I’ve used the Text Example (AS) in my Fla and have text scrolling across screen for 100 of 165 frames, the text will only scroll once, when the movie repeats the text doesn’t appear. New to Actionscript3 and not sure what I have to do to get the text to repeat. Can you help please.

  9. Hi Brian,

    Sorry for the delay… just noticed your question. If you have not figured it out, let me know – although if you are successful with the Falcon part then the rest is really up to you. ;-)

  10. I am also new to AS, and I’m having a devil of a time coming up with the following functionality: I want to bring XML data into a Flash file and allow the user to search on that data and return results to the movie. The XML file looks like this:

    1001121
    7558-02

    10.56
    Y

    1001181
    7557-02

    18.49
    Y

    1001191
    7557-04

    20.69
    Y

    So if the user searched on part number 7557, they’d get back two of the items listed in the XML file. Would Falcon be of any help to me in developing something like this? And can a newbie like moi figure out how to use it??

  11. Hi Nick,

    I have sent you an e-mail asking for the XML file in an attachment as this does not look like XML as displayed.

    Falcon will help you bring in the XML but it will be up to you to figure out how to access the data in the XML.

    Below is a Word document I wrote that might be of some help with respect to working with XML in Flash AS3:

    http://tinyurl.com/6eumhd

  12. Hi!
    I’m sorry if this is out of place, but my flash files stop displaying xml-info as soon as they get on the web. Falcon works brilliant locally on my machine. Did i miss a sandbox parameter or something?
    Thanks!

    • No… please, any questions just post them here, that is fine.

      You have not missed any sandbox issues as those would mean your local testing would be affected. Did you upload your xml to the server? Are you passing an absolute URL (htp://…) or a relative URL to Falcon?

      I will e-mail you for some more info…

  13. Thanks for the email with more info, Stain…

    You were trying to load XML from another server than your own. This can be done but you can’t read a file directly into Flash from someone else’s server unless you are in the authoring system or the sandbox or you get them to leave a domain trust file in their directory.

    What you do is use PHP (or a server script) on your server to read someone else’s file and then read the PHP result into Flash.

    The PHP, say otherfile.php would be like so:

    Then in your Flash, have Falcon call otherfile.php.

    It worked for me – see http://www.danzen.com/falcon/falcon/testXML.html for example.

    If you need any more help with it let me know.

    Dan

  14. I keep running into the same issue no matter where I look and that is the issue of being able to pass more than one variables. I am using PHP to connect to a database and pass that data to a SWF file. I have been able to get the falconVariables to work, but any idea as to how to pass more than one variable (I have three dynamic text boxes in the SWF file).

    falconVariables.as code:
    package falcon{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.text.TextField;
    public class FalconVariables extends MovieClip {
    public function FalconVariables() {
    var myFalcon:Falcon=new Falcon(“http://localhost/falcon/falconVariables.php”);
    myFalcon.addEventListener(Event.COMPLETE,getData);
    }
    private function getData(e:Event) {
    if (e.target.error) {
    myText.text = “sorry, error connecting to server script”;
    } else {
    myText.text = e.target.data.yourVariable;

    }
    }
    }
    }

    Thanks in advance – Sam

  15. Sure – you can pass multiple variables to and from Falcon like so:

    TO SEND MULTIPLE VARIABLES FROM FLASH TO PHP:

    make an object that holds the variables you want to send as properties and pass that object to Falcon as the third parameter:

    var myObject = new Object();
    myObject.text1 = yourText1.text;
    myObject.text2 = yourText2.text;
    myObject.text3 = yourText3.text;

    var myFalcon:Falcon=new Falcon("http://localhost/falcon/falconVariables.php", Falcon.VARIABLES, myObject);

    Then you can collect these in PHP as $_POST["text1"], etc.

    TO SEND VARIABLES BACK TO FLASH FROM PHP:

    You must echo only the variables in cgi format so that is url encoded format as follows:

    var1=value1&var2=value2&var3=value3, etc.

    In practice, in PHP it looks like this:

    $var1 = "some text that might have bad & or = etc.";
    $var2 = "some other info";
    $var3 = 22;

    echo "var1=".urlencode($var1)."&var2=".urlencode($var2)."&var3=".urlencode($var3);

    This should be the only line that PHP echoes. You should not have any line returns before the start of your PHP or after the end of your PHP

    In Flash, you would retrieve these variables with Falcon in the COMPLETE event method like so:

    trace (e.target.data.var1, e.target.data.var2, e.target.data.var3);

    You can use them however you want ;-)

    Hope this helps – if not, let me know.

    Dan

  16. Dan,

    Thanks for posting the new information. Being new to ActionScript 3 this is all rather confusing. I wonder if you could post the whole code instead of snippets for passing more then one variable.

    I understand the PHP code, it is the ActionScript that has me confused. Where does this new code go? Does it go in FalconVariables.as? As you know one mistake in ActionScript throws up a whole lot of errors.

    Thank you in advance – Sam

  17. Hi Sam,

    I have posted the code to show multiple variables back and forth between Flash and PHP in its basic form. Please see the following post:

    http://falconflash.wordpress.com/2009/02/01/passing-multiple-variables-between-flash-and-php/

    All the best and let me know if you have more questions.

    Dan

  18. Dan – You are a Prince for posting the new files on multiple variables.

    I got your version to work and so I am almost there. I don’t know if you can help me with the last part to complete my project, but I will ask you anyway.

    I have changed the falconMultipleVariables.html to index.php. A query is sent to the index.php (this by the way is a FileMaker database that is being queried with php). An example of the query would be “http://localhost/falcon/index.php?access_code=X35FV4″. As a result of the query, I can populate the index.php page fields from the database.

    How would I go about having that query return data from the falconMultipleVariables.php that would populate the dynamic text boxes in the Flash SWF file?

    Thanks in advance once again for your help – Sam

  19. Dan

    I solved my problem by using php $_SESSION.

    Again, thanks for your generosity – Sam

  20. Yes… I guess session variables could do it. The better way probably is to pass the id into Flash using FlashVars then send it back to PHP with Falcon to get the rest of the data from the database.

    In your index PHP you use this to get your access_code:

    $id = $_GET["access_code"];

    Then in the code that displays the flash you will see a line that says (do a search on this):

    'salign', ''

    adjust this to say:

    'salign', '',
    'FlashVars','id=<?PHP echo urlencode($id); ?>'

    note that there is a comma now after the first line there. What this does is passes your id into Flash. So in Flash, you find out the id like so:

    loaderInfo.parameters.id

    and put it into the object you are going to send via Falcon like so:

    myObject:Object = new Object();
    myObject.id = loaderInfo.parameters.id;

    Then send that off through Falcon to PHP, get your data coming back and put it into your text fields.

    ;-)

    Dan

  21. Dan – Hope you are not getting sick of me. (thanks for your reply to me last question, I see will see how it works).

    Because of the complexity of my project I am not able to use the ActionScript packages. What I am trying to do is have many swf files in different folders that are called through a query in php.

    Would it be possible for you to post the code you just created for passing multiple variables converted into the timeline like you have for your falconTimeLine.fla. I have tried to convert it myself, but can not get it to work.

    Thanks once again – Sam

  22. Hi Sam,

    When a swf is created all the classes that were used in it are compiled into the swf so you do not need to worry about having the classes around once it is compiled. As a matter of fact, you do not even need to post the classes on your server, etc.

    Let me know if that helps – if not, then I can transcribe the code to the timeline ;-)

  23. Dan

    Here is an issue now that I am using the FalconMultipleVariables.as: I have some button controls on the timeline and they do not work now. I did some searching around on the web a found that it seems to be an either or situation.
    How would I go about moving the code from the timeline to FalconMultipleVariables.as?

    Once again Thank You – Sam

  24. Hi Sam,

    You should be able to use both timeline scripts and scripts in classes in as files.

    But if you want to move the events into the as file you can. You will need to import the classes you are using – put this next to the other imports:

    import flash.net.URLRequest;
    import flash.net.navigateToURL;

    Then put your code in the constructor of the document class (FalconMultipleVariables.as in your case I think)

    One thing to watch out for is the button that you are putting the event on must be in existence when you try and add the event and must stay in existence as you use it.

    For instance, if you put your event code either in the as file or on the first frame of your fla and your button is on frame 10 then the event will not work. If your button is on the first frame but then the movie goes to another frame where your button is not, then the event will not work.

    This is one of the drawbacks of frames which lead coders to really only use multiple frames in MovieClips specifically for animations and rarely animations involving buttons. You can do it if you really want to by making sure the button exists on all frames with the same instance name and then hide it offstage on the frames you do not want it to show.

    Hope this helps.

    Dan

  25. I tried leaving the code I have four buttons in the timeline along with using your FalconMultipleVariables.as and get all sorts of error codes. As a result neither the buttons or the dynamic text works.

    Any ideas? – Sam

  26. Hi Sam – I will send you an e-mail and you can perhaps send me your code in a zip file in return and I can take a look.

  27. Greetings,

    Is there a way in which I can call differents URL’s without create a new Falcon Object every time???

    • I have had no problem calling Falcon over and over again – even every 50ms for local XML polling. Since it is a load and COMPLETE event really, I don’t think the events hang around or anything. I probably might have been more careful and removed the COMPLETE event or marked it for garbage collection once it loads but I never have removed COMPLETE events – I kind of thought they get rid of themselves automatically but maybe not. If anybody has any thoughts on this – please let me know.

Leave a Reply