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://[your server]/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="[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) {   
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'";   
return true;   
return false;   
function init(){   
	&& isSet($GLOBALS["clientPassword"])){   
	, $GLOBALS["clientPassword"])){   
printOutput("1", "Login successful.");   
} else {   
printOutput("0", "Failed to login $GLOBALS[clientUserName].");   
} 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 these ads

66 thoughts on “ActionScript 3: Using URLLoader to send and load server variables

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

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

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

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


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

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

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

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

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

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

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

  12. What happens if in the function

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

    the variable $code has the character “&”?

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

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

  15. Hi,

    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

  16. 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,


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

    I am using linux.

  18. […] Namen gleich beim Klicken aufrufen! (ActionScript 3.0) und noch ein Beispiel: ActionScript 3: Using URLLoader to send and load server variables Tushar Wadekar mfg […]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  33. 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?

  34. 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? :-P 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?

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

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

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

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s