Here is a very simple example of two way communication with database using Flex and PHP. In this example, we are sending username and password to the PHP file from Flex. PHP file then validates the input and returns the appropriate response.
This example also demonstrates the simple PHP script to establish a database (MySQL) connection and validate username and password against the table in database.
In AS3, we can use flash.net.URLLoader, URLRequest and URLVariables class to send and load data. First create a class named SendAndLoadExample.
Class SendAndLoadExample:
package {
import flash.events.*
import flash.net.*;
public class SendAndLoadExample {
public function SendAndLoadExample() {}
public function sendData(url:String, _vars:URLVariables):void {
var request:URLRequest = new URLRequest(url);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request);
}
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
trace("Par: " + loader.data.par);
trace("Message: " + loader.data.msg);
}
private function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");
}
}
}
Now, create an object of SendAndLoadExample class in Flex.
SendAndLoadExample.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">
<mx:Script>
<![CDATA[
import flash.net.URLVariables;
private var mySendAndLoadExample:SendAndLoadExample;
mySendAndLoadExample = new SendAndLoadExample();
private function sendAndLoad():void {
var url:String = "http://[your server]/login.php";
var variables:URLVariables = new URLVariables();
variables.UserName = "tushar";
variables.Password = "my_password";
mySendAndLoadExample.sendData(url, variables);
}
]]>
</mx:Script>
<mx:Button label="Fetch data" click="sendAndLoad()"/>
</mx:Application>
PHP Script for login check: login.php
<?
$clientUserName=$_POST['UserName'];
$clientPassword=$_POST['Password'];
//////////////////////////////////////
// Host name
$host="[your server]";
// Mysql username
$username="[MySql database username]";
// Mysql password
$password="[MySql database password]";
// Database name
$db_name="[MySql database name]";
// Table name
$tbl_name="[MySql table name having usernames and passwords]";
function makeConnection() {
// Connect to server and select databse.
mysql_connect("$GLOBALS[host]", "$GLOBALS[username]",
"$GLOBALS[password]")or die("cannot connect");
mysql_select_db("$GLOBALS[db_name]")or die("cannot select DB");
}
function fireQuery($query) {
$result=mysql_query($query);
return $result;
}
function printOutput($code, $msg){
print "par=$code&msg=$msg";
}
//////////////////////////////////////
function checkUserID($id, $password) {
$sql="SELECT * FROM $GLOBALS[tbl_name] WHERE
userName='$id' and password='$password'";
$result=fireQuery($sql);
$count=mysql_num_rows($result);
if($count==1){
return true;
}
return false;
}
function init(){
if(isSet($GLOBALS["clientUserName"])
&& isSet($GLOBALS["clientPassword"])){
makeConnection();
if(checkUserID($GLOBALS["clientUserName"]
, $GLOBALS["clientPassword"])){
printOutput("1", "Login successful.");
} else {
printOutput("0", "Failed to login $GLOBALS[clientUserName].");
}
} else {
printOutput("0", "Required parameters missing.");
}
}
init();
?>
However, you can also use HTTPService to send and load data in Flex. Nitin has posted a simple example of using HTTPService in flex. Check it out here.




Good post. I picked up a few thangs..
By: B on November 12, 2007
at 10:46 pm
Hello
I am new to AS3 development. I am stuck at one problem for quite some time now. Can anyone please tell me how to send XML data using URLRequest.POST method?
It seems that when I send a simple xml data using this nothing is received at the server side I have used both PHP and ASP.NET
Thanks in advance
By: Adnan on March 30, 2008
at 9:35 pm
great blogs thanks i learned a few things
By: Schools on April 26, 2008
at 7:22 pm
Like Adnan, I am confused about how to send an AS3 XML object. I need the same functionality that the AS2 sendAndLoad method provides.
Any ideas would be very very much appreciated.
By: Sander on May 1, 2008
at 5:37 am
You can achieve the same effect as AS2 sendAndLoad by supplying a callback Function. Then use a custom URLLoader that can store this Function and have it call this Function after Event.COMPLETE is dispatched by the loader.
I don’t think pasting tons of code in this comment helps, but here’s what an example function header might look like:
public function sendAndLoad(url:String, variables:URLVariables, callback:Function):void
And you’d catch Event.COMPLETE with a function that looks something like:
private function getResponse(e:Event):void {
loader = e.target as CustomURLLoader;
loader.callback(loader.data);
}
Where callback() is the Function that you passed as a parameter previously that is now held as a variable by your CustomURLLoader.
By: Kai on August 14, 2008
at 8:36 pm
Rather than writing all kinds of php, asp, or java files for each query to your DB check out the Peak Studios DB extension for flash you can always use the classes in Flex. Saves me hours of time every time I use the extension (in flash) or the AS classes (in Flex).
This is a good tutorial but rewriting those files and using fiddler or AMFPHP for error detection is very time consuming.
Thanks!
Quince
By: Quince on October 12, 2008
at 5:13 pm
you know. there is a syntaxhighlighter wordpress plugin ….
By: friendly on October 16, 2008
at 3:54 pm
Hello,
I use URLLoader class with load() method who load an XML stream from a PHP file. COMPLETE event launch a fonction, everything works great ! Except one time out of ten…
WHY ? here s a element of response : I tried the same with a .xml file instead of a PHP stream, and it works ALLWAYS (even with a 1MB .xml). The conclusion is that Flash read an XML stream that the PHP IS SOMETIMES STILL WRITING. So the bug appears. How to avoid that ?
This is a FlashPHP project where every client action reload an XML stream provded by PHP, ay advices.
Merci énormément, this is very important.
Sylvain.
By: shawee on November 16, 2008
at 2:36 pm
Hello, thx for all,
By: name on January 5, 2009
at 6:47 am
well I´m really starting with all these things Flex, AS3 etc and I need to enhance my knowledge about it. So I found so interesting this post, useful and very very helpful to me!! =) Thanks for the post!
Well actually all issues in this Blog are totaly usful!!!
By: Flüge on January 6, 2009
at 11:57 am
thanks!
By: powerslave on February 4, 2009
at 4:49 pm
Excellent Dude, Thanks for sharing.
By: Alfie Punnoose on February 27, 2009
at 8:02 am
Hi!
I ‘m trying to compile your sample in Flex 3.
I placed the
SendAndLoadExample.mxml
and
SendAndLoadExample.as
in the
/SendAndLoadExample/src
before compiling I have this error:
1061: Call to a possibly undefined method sendData through a reference with static type SendAndLoadExample. SendAndLoadExample/src SendAndLoadExample.mxml
By: Brian Anotado on March 4, 2009
at 4:07 am
[...] SendAndLoadExample: view plaincopy to [...]
By: Using URLLoader to send and load server variables « Tuan Anh’s Blog on March 11, 2009
at 4:15 am
I read your blog for a long time and should tell you that your articles always prove to be of a high value and quality for readers.
By: Vince Delmonte on April 14, 2009
at 8:58 pm
Храни себя от бед пока их нет
By: chmobl on May 19, 2009
at 1:35 pm
Hi,
i want to know… i am preparing an application, suppose there are 5 games, as the game 1 is loaded and running i want all the assets of game 2 to be loaded in the background… how is it possible can anyone help. Game 2 has a swf, images and sound to load via xml.
By: nitin on May 26, 2009
at 9:54 am
I have been trying to communicate with a php script for days now…
I have pretty much copied this exact code, except my php is much simpler and just echos a response back immediately. The problem I’m having is I can’t access anything I send back to flash. When I check the contents of events.target.data I get the entire php script code with all the %’s and random crap. I also have a statement like ‘echo “score=”+$score’ in my php code and when I try to access it in flash with this code: evt.target.data.score I get undefined back. My php script is also supposed to create a file which it is not doing. It seems like the php script is not being executed. Any thoughts/suggestions would be greatly appreciated. Been banging my head on this for days.
By: porksoday on June 10, 2009
at 5:34 pm
@porksoday
Posted an example of what your trying to do, see the link.
http://lookatmyfreakin.blogspot.com/2009/06/send-and-load-data-via-flash-as3.html
By: Crypton on June 14, 2009
at 10:56 pm
Nice Post. Helped me a lot. Thanks
By: Rana on July 2, 2009
at 12:40 pm
Read more hot reports about Business, Form business or Women small business loans http://business.goodnano-av.com/
By: Neubrekitourb on July 6, 2009
at 12:42 pm
Haven’t laughed so stern benefit of years! That was a honest expound on! Assault watch The Hangover You are thriving to infatuation it!! Reminds me my Las vegas
By: Merskenor on July 12, 2009
at 7:10 am
thanks a bunch!
By: Ben on August 24, 2009
at 6:38 pm
А если посмотреть на это с другой точки зрения то не все так гладко получается
By: Sergio on October 4, 2009
at 8:41 am
What happens if in the function
function printOutput($code, $msg){
print “par=$code&msg=$msg”;
}
the variable $code has the character “&”?
By: tan on October 23, 2009
at 8:28 am
amazing stuff thanx
rH3uYcBX
By: Viagra on January 23, 2010
at 7:12 pm
You are perfect!
I am too many time finding it, very nice and wonderful working.
Thanks again!
By: atasözleri on February 25, 2010
at 10:42 am
A quick and dirty way to get the same result is to do the following (Note the IF statement is for flash testing only b/c since there are no variables in the URL when you test in flash, it’ll throw an error until you test it in a browser…)
var1=ExternalInterface.call(‘window.location.href.toString’);
if (var1!=undefined) {
// take the URL and split it on the variable name -gets put into an array.
var1=var1.split(‘var1=’);
//get variable data from array
var1=var1[1];}
else {
var1=’testing in Flash environment…’
}
NOTE: Need to import:
import flash.external.*;
By: mara on March 3, 2010
at 9:05 pm
—Quote Start—
What happens if in the function [...] the variable $code has the character “&”?
—Quote End—
Maybe it should be:
function printOutput($code, $msg){
print “par=”.urlencode($code).”&msg=”.urlencode($msg);
}
By: Alex on March 5, 2010
at 8:22 pm
wow this tutorial is old (July 2007), but very nice. Thanks
-Son
http://www.sonsoftco.com
New Web Design and Flash Games – SonSoft Company
By: Sonsoftco.com on April 2, 2010
at 7:29 pm
[...] [...]
By: Statstabelle aus Datenbank lesen+Anzeigen - Flashforum on April 25, 2010
at 8:40 am
[...] [...]
By: Sichergehen das XML geschrieben wurde... - Flashforum on August 25, 2010
at 8:43 pm
Hi,
I have the same problem as porksoday and would really appreciate any help.
PHP CODE:
AS3 CODE:
var myrequest:URLRequest = new URLRequest(“get_pdf_name.php”);
myrequest.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader (myrequest);
loader.addEventListener(Event.COMPLETE, get_name);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(myrequest);
function get_name(e:Event)
{
var variables:URLVariables = e.target.data;
var mypdfname = e.target.data.pdfname;
trace(“Variables: “+variables);
trace(“PDF Name: “+mypdfname);
}
RESULT:
Variables: %3C%3Fphp%0A%0Aecho%20%28%27pdfname=MYPDFNAME%27%29%3B%0A%0A%3F%3E
PDF Name: undefined
Comments:
‘variables’ holds the entire php code (looks like the php file is not executing)
I made sure the .fla file and php file are on my local web server (therefore php must run). Flash basically treats the php as a text file and returns the content. How can I solve this problem? what am I missing? please help!
Thanks in advance
By: Khaled on December 2, 2010
at 8:44 am
for those who have the same problem, I have gotten it to work:
php code:
as3 code (this i placed in the actions window – i.e. on frame one):
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.text.*;
var mycontent:TextField;
var mycontent1:TextField;
var mycontent2:TextField;
var mycontent3:TextField;
var mycontent4:TextField;
var myrequest:URLRequest = new URLRequest(“get_pdf_name2.php”);
myrequest.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader (myrequest);
loader.addEventListener(Event.COMPLETE, get_name);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(myrequest);
function get_name(e:Event)
{
var variables:URLVariables = e.target.data;
mycontent.text = variables.toString();
mycontent1.text = variables.name;
mycontent2.text = variables.age;
mycontent3.text = variables.height;
mycontent4.text = variables.weight;
trace(“Variables: “+variables);
trace(“Name: “+variables.name);
trace(“Age: “+variables.age);
trace(“Height: “+variables.height);
trace(“Weight: “+variables.weight);
}
This only works on the server host, not my local apache server. I thought it was because register_globals was turned off but that turned out not to make difference.
In terms of the code the only thing I did differently from before, was create ‘Dynamic text fields’ and give them instance names and just assign the return php values directly to them.
In any case, still not sure why it doesn’t work locally but I don’t really care at this point just need to move on!
Hope this helps,
Cheers
By: Khaled on December 5, 2010
at 8:41 am
php code:
$myName = ‘khaled’;
print(‘name=’.$myName.’&age=five&height=34&weight=heavy’);
By: Khaled on December 5, 2010
at 8:42 am
LWDPL4 http://chfEd38MkKsw7cXv0x3Dlc3b7.com
By: jimmy on January 22, 2011
at 1:47 am
Awesome all the time to see how people who can write wonderful things the theme! Thank you! christian is a highly recommended brand!
By: UnsataHausa on March 10, 2011
at 7:21 pm
how can I call a local perl code ( both mxml and perl file are in same directory) from mxml file ?
I am using linux.
By: mac on March 11, 2011
at 9:12 am
I quite simply get an IOError that says “Error loading URL: http://myUrlGoesHere/sthsth.php” how can I overcome this? any help would be appreciated.
By: pelin soykan on August 16, 2011
at 7:35 am
How do you change the timezone in linux?
By: Linux VPS Hosting on September 4, 2011
at 2:09 am
Nice tut.. but i want to know
How can I save data by using Flash AS 3.0 User Detail Form with Asp.net and save that data in Sql Server … .
Please Help..
By: Vishal on September 14, 2011
at 11:57 am
Your site is pretty interesting to me and your subject matter is very relevant. I was browsing around and came across something you might find interesting. I was guilty of 3 of them with my sites. “99% of blog owners are committing these five errors”. http://bit.ly/uw1s4S You will be suprised how easy they are to fix.
By: five mistakes on December 9, 2011
at 4:13 pm
I’m still learning from you, while I’m making my way to the top as well. I certainly liked reading all that is posted on your website.Keep the posts coming. I loved it!
By: http://andcarinsurancequotes.com on March 19, 2012
at 10:30 am
There are lots of sites on the internet that describe quite nicely how a sinus headache
feels. The syndrome happens in one or two weeks before menstruation and
then declining when the period starts. Few common types of headache are Tension headache,
Migraine headache and sinus headache.
By: dureri de cap on November 15, 2012
at 6:01 am
When you have a minor assert, establish whether it is worth
every penny to submit along with your vehicle insurance organization.
The policy offers financial assistance to repair your car and get it back on track.
Unfortunately, Jake also suffered a broken wrist and some whiplash.
By: pinterest.com on December 4, 2012
at 11:59 pm
it is very helpful thanks
By: pejman on January 9, 2013
at 2:15 pm
Good day! This is kind of off topic but
I need some help from an established blog.
Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but
I’m not sure where to begin. Do you have any ideas or suggestions? Thanks
By: ginecologie on February 7, 2013
at 8:17 am
We simply understand the symbolic dream language so that you can have a direct communication
with all the wise unconscious mind. This could possibly be like a three yr old trying to cope with the world.
Thus, I could better comprehend the unconscious lessons.
By: Psihoterapie bucuresti on March 22, 2013
at 11:11 pm
It concentrates on how we sit, stand, bend, lift, and even the way you sleep.
Improving strength and adaptability go hand in hand.
A hormone called relax in is produced by your system during pregnancy.
By: dureri de spate on April 7, 2013
at 2:29 pm
If some one wants expert view about blogging afterward i recommend
him/her to pay a quick visit this weblog, Keep up the nice work.
By: ginecologie on April 15, 2013
at 12:57 am
Thank you for any other informative web site. Where else may just
I get that kind of info written in such a perfect means? I have a venture that I’m just now working on, and I have been on the look out for such info.
By: fat burner zsírégeto on April 18, 2013
at 1:39 pm
The vacuum created from the disc aids to get any herniated or protruded disc material
back into the disc and stimulate blood flow, and thereby accelerate the healing process.
Also, the symptom could are the inability to boost the big toe on upward direction.
One teaspoonful of triphala needs to be given
to the person, blended with a cup of warm milk then one spoon of sugar.
By: spondiloza on April 21, 2013
at 2:41 am
I’m truly enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much
more enjoyable for me to come here and visit more often.
Did you hire out a developer to create your theme? Fantastic
work!
By: gate13.net on May 8, 2013
at 9:48 pm
Pain is created from inflammation and pressure which reduces the joint variety of motion.
If you need to have this procedure done to you, it is usually effective when it was done properly.
Chiropractic care helps relieve lower back pain safely and effectively.
By: hernie de Disc on May 17, 2013
at 6:29 am
I have been browsing online more than 3 hours today, yet I never found any interesting article like
yours. It’s pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did, the internet will be a lot more useful than ever before.
By: Cynthiazanon.Blogspot.Com on May 18, 2013
at 2:21 am
This implies that you have the work and the psychotherapies of two generations of researchers guaranteeing you the success of dream therapy.
Behavioral therapy works in the somewhat similar way, by praoclaiming
that almost every mental dilemma is a consequence of repetitive
incorporation in to a person. The role of psychotherapy (the Danes
utilize term l.
By: psihoterapie on May 21, 2013
at 12:59 am