ActionScript 3: Using URLLoader to send and load server variables

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, URLRequest and URLVariables class to send and load data. First create a class named SendAndLoadExample.

Class SendAndLoadExample:

package {


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; = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(;
trace("Par: " +;
trace("Message: " +;
private function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");

Now, create an object of SendAndLoadExample class in Flex.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" 
private var mySendAndLoadExample:SendAndLoadExample;
mySendAndLoadExample = new SendAndLoadExample();
private function sendAndLoad():void {
var url:String = "http://&#91;your server&#93;/login.php";
var variables:URLVariables = new URLVariables();
variables.UserName = "tushar";
variables.Password = "my_password";
mySendAndLoadExample.sendData(url, variables);
<mx:Button label="Fetch data" click="sendAndLoad()"/>

PHP Script for login check: login.php

// Host name   
$host="&#91;your server&#93;"; 
// Mysql username
$username="&#91;MySql database username&#93;"; 
// Mysql password     
$password="&#91;MySql database password&#93;"; 
// Database name    
$db_name="&#91;MySql database name&#93;"; 
// Table name  
$tbl_name="&#91;MySql table name having usernames and passwords&#93;";  
function makeConnection() {   
// Connect to server and select databse.   
mysql_connect("$GLOBALS&#91;host&#93;", "$GLOBALS&#91;username&#93;", 
		"$GLOBALS&#91;password&#93;")or die("cannot connect");   
mysql_select_db("$GLOBALS&#91;db_name&#93;")or die("cannot select DB");   
function fireQuery($query) {   
return $result;   
function printOutput($code, $msg){   
print "par=$code&msg=$msg";   
function checkUserID($id, $password) {   
$sql="SELECT * FROM $GLOBALS&#91;tbl_name&#93; WHERE 
		userName='$id' and password='$password'";   
return true;   
return false;   
function init(){   
	&& isSet($GLOBALS&#91;"clientPassword"&#93;)){   
	, $GLOBALS&#91;"clientPassword"&#93;)){   
printOutput("1", "Login successful.");   
} else {   
printOutput("0", "Failed to login $GLOBALS&#91;clientUserName&#93;.");   
} else {   
printOutput("0", "Required parameters missing.");   

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.


About Tushar

Hi, I am Tushar Wadekar from Pune, India. I am an Adobe Certified Flash Developer. My Interests are: Flash, ActionScript, Flex, AIR, PHP, Ruby on Rails. You can reach me at: tusharwadekar[at]gmail[dot]com Thank you! Tushar
This entry was posted in ActionScript3, AS3, Database, Flash CS3, Flex, MySql, PHP. Bookmark the permalink.

71 Responses to ActionScript 3: Using URLLoader to send and load server variables

  1. B says:

    Good post. I picked up a few thangs..

  2. Adnan says:


    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

  3. Schools says:

    great blogs thanks i learned a few things

  4. Sander says:

    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.

  5. Kai says:

    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 = as CustomURLLoader;

    Where callback() is the Function that you passed as a parameter previously that is now held as a variable by your CustomURLLoader.

  6. Quince says:

    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.


  7. friendly says:

    you know. there is a syntaxhighlighter wordpress plugin ….

  8. shawee says:


    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.

  9. name says:

    Hello, thx for all,

  10. Flüge says:

    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!!!

  11. powerslave says:


  12. Excellent Dude, Thanks for sharing.

  13. Brian Anotado says:

    I ‘m trying to compile your sample in Flex 3.
    I placed the
    in the

    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

  14. Pingback: Using URLLoader to send and load server variables « Tuan Anh’s Blog

  15. 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.

  16. chmobl says:

    Храни себя от бед пока их нет

  17. nitin says:


    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.

  18. porksoday says:

    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 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: 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.

  19. Crypton says:


    Posted an example of what your trying to do, see the link.

  20. Rana says:

    Nice Post. Helped me a lot. Thanks

  21. Read more hot reports about Business, Form business or Women small business loans

  22. Merskenor says:

    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

  23. Ben says:

    thanks a bunch!

  24. Sergio says:

    А если посмотреть на это с другой точки зрения то не все так гладко получается

  25. tan says:

    What happens if in the function

    function printOutput($code, $msg){
    print “par=$code&msg=$msg”;

    the variable $code has the character “&”?

  26. Viagra says:

    amazing stuff thanx 🙂


  27. atasözleri says:

    You are perfect!

    I am too many time finding it, very nice and wonderful working.

    Thanks again!

  28. mara says:

    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…)‘window.location.href.toString’);

    if (var1!=undefined) {

    // take the URL and split it on the variable name -gets put into an array.


    //get variable data from array


    else {

    var1=’testing in Flash environment…’


    NOTE: Need to import:

    import flash.external.*;

  29. Alex says:

    —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);

  30. wow this tutorial is old (July 2007), but very nice. Thanks

    New Web Design and Flash Games – SonSoft Company

  31. Pingback: Statstabelle aus Datenbank lesen+Anzeigen - Flashforum

  32. Pingback: Sichergehen das XML geschrieben wurde... - Flashforum

  33. Khaled says:


    I have the same problem as porksoday and would really appreciate any help.


    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;
    function get_name(e:Event)
    var variables:URLVariables =;
    var mypdfname =;

    trace(“Variables: “+variables);
    trace(“PDF Name: “+mypdfname);

    Variables: %3C%3Fphp%0A%0Aecho%20%28%27pdfname=MYPDFNAME%27%29%3B%0A%0A%3F%3E
    PDF Name: undefined

    ‘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

  34. Khaled says:

    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.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;

    function get_name(e:Event)
    var variables:URLVariables =;
    mycontent.text = variables.toString();
    mycontent1.text =;
    mycontent2.text = variables.age;
    mycontent3.text = variables.height;
    mycontent4.text = variables.weight;

    trace(“Variables: “+variables);
    trace(“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,


  35. Khaled says:

    php code:

    $myName = ‘khaled’;


  36. UnsataHausa says:

    Awesome all the time to see how people who can write wonderful things the theme! Thank you! christian is a highly recommended brand!

  37. mac says:

    how can I call a local perl code ( both mxml and perl file are in same directory) from mxml file ?

    I am using linux.

  38. Pingback: Anonymous

  39. pelin soykan says:

    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.

  40. How do you change the timezone in linux?

  41. Vishal says:

    Nice tut.. but i want to know
    How can I save data by using Flash AS 3.0 User Detail Form with and save that data in Sql Server … .

    Please Help..

  42. 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”. You will be suprised how easy they are to fix.

  43. says:

    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!

  44. 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.

  45. 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.

  46. pejman says:

    it is very helpful thanks

  47. ginecologie says:

    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

  48. 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.

  49. 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.

  50. ginecologie says:

    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.

  51. 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.

  52. spondiloza says:

    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.

  53. says:

    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

  54. 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.

  55. 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.

  56. psihoterapie says:

    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.

  57. Ellie says:

    Right now it looks like WordPress is the preferred blogging platform out there right now.
    (from what I’ve read) Is that what you are using on your blog?

  58. says:

    Hi, I want to subscribe for this weblog to obtain newest updates, therefore where can i do it please assist.

  59. What’s up, its good piece of writing on the topic of media print, we all understand media is a impressive source of facts.

  60. 外燴 says:

    I love to share information that I’ve built up with the 12 months to assist enhance team functionality.

  61. I don’t leave a comment, but after looking at through a ton of comments on ActionScript
    3: Using URLLoader to send and load server variables | Tushar Wadekar.
    I do have a couple of questions for you if you do not mind.
    Is it only me or does it appear like a few of these comments come across
    like they are left by brain dead folks? 😛 And, if you are posting on additional online social sites, I would like
    to keep up with you. Would you make a list of the complete
    urls of all your public sites like your Facebook page, twitter
    feed, or linkedin profile?

  62. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your blog?
    My blog is in the exact same area of interest as yours and my
    users would truly benefit from some of the information you
    present here. Please let me know if this okay with you.
    Thanks a lot!

  63. rea says:

    You really make it seem so easy with your
    presentation but I find this matter to be really
    something whicch I think I would never understand.
    It seems too complicated and extremely broad for me.
    I’m looking forward for your next post, I will
    try to get the hng of it!

  64. Pretty nice post. I just stumbled upon your weblog and wished to say that I have truly enjoyed
    surfing around your weblog posts. After all I will be subscribing for your
    feed and I’m hoping you write again very soon!

  65. ____________ says:

    When the cyclist has reached the finish of the energy level provided by the last meal, turn the motor on for the bicycle and
    enjoy the rest of the ride. Attach the electric supply controller box to the frame.
    Take your electric motorized bike on vacation with you and see more
    in less time. While they are primarily selling in Europe, the bikes are available in the
    US through a sales representative.

  66. Maqui Berry, else known as Chilean wineberry or aristotelia chilensis is a
    plant effectively used for the treatment of over weight or obesity.
    Thoughts of fear and negative emotions can trick you into believing you’re better off in your
    current situation. How much easier does it get when everything you need can be where you need it, when you need it.

  67. Pingback: not able to pass data from local swf to remote PHP - Tech Magazine

  68. Michaellamb says:

    dumps – dumps forum 2017, cvvshop.

  69. My partner and I stumbled over here different web page and thought I might buy viagra free shipping. I like what I see so i am just following you. Look forward to looking into your web page yet again.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s