Send and load variables with AS3 and PHP
February 21, 2009 by: ChristianBecause I use this all the time I decided to put the handling of loading variables with AS3 and PHP in a handy little class. The usage is really simple:
new VarLoader("yourscript.php",{var1:value1, var2:value2})
But before explaining everything in detail, lets look at this example:
The complete AS3 code in varloader.swf:
import net.kaegi.loaders.VarLoader;
var vl:VarLoader;
//
sendBtn.addEventListener(MouseEvent.CLICK,sendBtnHandler);
function sendBtnHandler(e:MouseEvent) {
// Variables sent by POST-Method:
var varObj:Object = {};
varObj.textinput0 = escape(textinput0.text);
varObj.textinput1 = escape(textinput1.text);
// additionally another variable is sent by the GET method:
vl = new VarLoader("http://www.flashcmsframework.ch/wp-content/data/varloader/varloader.php?var_get=I was sent by GET!", varObj);
vl.addEventListener(Event.COMPLETE, onVarsLoaded);
vl.addEventListener(Event.CANCEL, onVarsCancel);
}
function onVarsLoaded(e:Event) {
var msg:String = "Communication with the server was successful.\n\n";
msg += "bulla -> "+e.target.vars.bulla+"\n";
msg += "gogull -> "+unescape(e.target.vars.gogull)+"\n";
msg += "var33 -> "+unescape(e.target.vars.var33)+"\n";
msg += "var_get -> "+unescape(e.target.vars.var_get)+"\n";
msg += "textinput0 -> "+unescape(e.target.vars.textinput0)+"\n";
msg += "textinput1 -> "+unescape(e.target.vars.textinput1)+"\n";
tf_servermsg.textColor = 0x009900;
tf_servermsg.text = msg;
}
function onVarsCancel(e:Event) {
tf_servermsg.textColor = 0x990000;
tf_servermsg.text = e.target.errormsg;
}
…and the code in varloader.php:
// coming from flash (GET) $var_get = $_GET["var_get"]; // coming from flash (POST) $textinput0 = $_POST["textinput0"]; $textinput1 = $_POST["textinput1"]; // internal $bulla = "Blabla. I am just some lonely text....."; $gogull = "WOW! I was fetched from the server as well! Cool!"; $var33 = "Hey, my name is 'var33'! What's yours?"; // result: $result = "foo=bar"; // In AS3 the first variable MUST NOT have an '&', otherwise you will get an error message! So just use some dummy vars to make flash happy. $result .= "&bulla=".rawurlencode($bulla); $result .= "&gogull=".rawurlencode($gogull); $result .= "&var33=".rawurlencode($var33); $result .= "&var_get=".rawurlencode($var_get); $result .= "&textinput0=".rawurlencode($textinput0); $result .= "&textinput1=".rawurlencode($textinput1); echo $result; ?>;
Download source code and example file
I hope someone can use this!
Update 12/28/2009: Some useful links regarding url encoding:
escape()
unescape()
encodeURI()
encodeURIComponent()
decodeURI()
decodeURIComponent()
Cheers,
Christian






Thanks for an excellent tutorial…
@Sadaf
You’re welcome!
Thanks a lot, you just saved the life of one programmer.
Your tut is full of win. +7 internets and kudos to you, man.
Great! Thanks a lot.
vry tnx
haha, one month later, your handy little class saved me again. Double thanx!!
Dude, you saved my life!
Thank you very, very much.
All the best!
Wow, I’m a lifesaver! That’s cool…
Amazing post! thank you!
Super! You are quite generous. Thank you for the knowledge share!
Thank you. It did the trick.
Thanx, man! Thought in AS3 it wasn’t possible… good job!
shortcut and cool. thanks
hi..
nice work.
how can load a php Array or object..?
You can serialize your arrays or objects and convert it in flash again by using “split”. For example like this:
PHP: $result = “&myarray=”.rawurlencode($v1).”{“.rawurlencode($v2).”{“.rawurlencode($v3);
AS3: var myarray:Array = e.target.vars.myarray.split(“{“)
or, if more complex, use JSON.
Interesting, I wrote a AS3 to PHP class that does the same exact thing. check it out at
http://www.as3blog.org/?p=18 ..This turns out to be a very useful class. Most of my site’s traffic comes to this link!
i need multidimensional Array loading.
can i load through flashvars..?
真的相當實用!非常感謝您!
Hi, i did used, but i received error:
”
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: localhost:8080/c/varloader.php?var_get=I was sent by GET!
at net.kaegi.loaders::VarLoader/init()
at net.kaegi.loaders::VarLoader()
at varloader_fla::MainTimeline/sendBtnHandler()
“
@thanh
When you download the source files, open “varloader.fla” and publish it it’s working, right? You are testing it on the localhost, so there has to be something there or in the varloader.php itself.
Hey.. I cannot download the source codes for this example..
What exactly is the problem? I just checked it, it’s working…
Hi Christian,
When I clicked “Download source code and example file” it directed me to a page which says “// You cannot download this file” and its url is “http://www.turtlebite.com/mint/pepper/tillkruess/downloads/tracker.php?url=http%3A//blog.turtlebite.com/wp-content/data/varloader/varloader.zip”.
But I could download the files from “//blog.turtlebite.com/wp-content/data/varloader/varloader.zip”.
Thanks for the excellent tutorial. I used LoadVars in AS2 and this is way advanced in AS3.
Nice Work..
Sam
Ah, I see, that’s just a redirect for statistics (haveamint.com). But if you could manage to download it now, that’s perfect,
Cheers,
Christian
thanks.
It won’t let me download the source files. Any reason for that?
i get this message
// You cannot download this file
Nevermind. I read the rest of the posts and got the answer to my dilemma.
Thanks!
Hi There,
Where should I put VarLoader.as file in order to be able to use varloader?
Thanks,
Richk
It should be in the folder “net/kaegi/utils”. Just have a look at the files you just downloaded (http://blog.turtlebite.com/wp-content/data/varloader/varloader.zip), all you need is there.
I cant download the source. Need some help please
What error message do you get?
Thanks, it’s very helpful for me.
http://www.as3tutorial.com is very helpful for beginners.
A strange issue with me if use ” : ” in var_get variable script stop working if remove ” : ” script starts working. Can somebody let me know what is the logic behind this while if you paste url directly in browser with post and get variables php file works fine this means there is an issue with class file. Check using this
vl = new VarLoader(“varloader.php?var_get=I was sent by : GET!”, varObj);
Hi Nomi
This is not strange.
If you send data using the GET Method you should urlencode the string to convert all “bad” characters like : ; ” & <> and so on. Or you use the POST method. In the example, you can see that the values sent by the POST method are “escaped” in Flash.
Cheers,
Christian
Hi Christian, “I cannot download the file” again … can you send me please ? TY
Just danced in my chair, but that wasn’t enough so I got up and danced around the room. I’ve been trying to figure this out for a few days and had pretty much gotten no where until I finally found this.
Thank you!!!!!!!!!!!!!!!!!!! x 1 million bajillion
-Joey
You’re very welcome!
)
Works perfectly but I’m not able to get the php file to display the text input 0 and 1. What php/html code do I need to add so that the .php file on my server displays that string? I don’t know much about php but I’ve tried to echo and print the strings, which hasn’t worked.
If I wrote that wrong, my goal is to have a user type a name, click send, and then display their score (as a string) and input name (as a string) in a php/html file. I’m guessing theres a little piece of php I can use to display the strings.
Thank you,
Joey
Hi Joel
I don’t know exactly what the problem is you are describing. When I enter some text in the form above and hit “Send”, it is displayed in the textfield below. So if you download the files and check them out it should work… All you need is in those files. Or am I missing something? (BTW, I will be away for 2 weeks from tomorrow, and I won’t have an internet connection…)
Yes, they are displayed in the flash text box. I would like a visitor to be able to see the text in the PHP file.
e.g. The user types there name in the flash program and presses Send, then anyone can see what they typed if they go to mysite.com/phpfile.php
Sorry, I hope that makes sense, and have a nice trip,
-Joey
working on some mysql/php/as3 at the moment and pulling variables from the database and displaying them as individual values is possible with help from this tutorial.
thanks for the help.
Hi,
Can I ask, in the old Action Script 2, I could target _blank, how would I do that here.
I Want to post vars to a c# file which then streams back a CSV, In the old SendAndLoad days I would simply target _blank and viola users could generate file downloads at a click.
Any ideas?
C
Try (and/or google) this:
var req:URLRequest = new URLRequest(“http://……”);
navigateToURL(req, “_blank”);
Cheers,
Christian
The Download isnt working. It says “// You cannot download this file”.
Ugh…
It’s in Firefox sometimes a problem. Copy and paste this link: http://blog.turtlebite.com/wp-content/data/varloader/varloader.zip
Cheers,
Christian
I cant get this to work online, it works local but once i upload it nothing happens when i press send, can some of the functions be blogged serverside or am i doing something wrong? my webhost supports both php and flash..
Please help
Hi
Sorry for the delay. Is it still not working?
hey… I tried this code but doesn’t seem to work for me.. for start I need only to run a php script from local (parameters doesn’t matter now) and when I run the html file with swf embed doesn’t run the script
using navigateToURL works without any problems but if i use the function VarLoader doesn’t work anymore… the script should open a force download for an image located on localhost
Here’s my code:
var varObj:Object = {};
varObj.textinput0 = escape(“arrrrr”);
varObj.textinput1 = escape(“grrrrr”);
var vl:VarLoader=new VarLoader(“http://localhost/website/download.php”,varObj);
should I need to add something else in order to work?
Have you tried out the example files? You should add the event Listener vl.addEventListener(Event.COMPLETE, onVarsLoaded); in order to know when then vars are loaded.
your example doesn’t work for me… i even tried with xampp(i guess you can’t run php scripts without a server) but still nothing happens… something fishy is going here;
before i tried your class, i used this code:
var vars:URLVariables = new URLVariables();
vars.filename = “http://localhost/website/gallery/images/img1.jpg”;
var req:URLRequest = new URLRequest(“http://localhost/website/download.php”);
req.method = URLRequestMethod.POST;
req.data = vars;
var loader2:URLLoader = new URLLoader(req);
loader2.addEventListener(Event.COMPLETE, onDataIn);
loader2.dataFormat = URLLoaderDataFormat.VARIABLES;
loader2.load(req);
but didn’t work
any ideas what could be the problem?