Posted by: Tushar | July 20, 2007

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

About these ads

Responses

  1. Good post. I picked up a few thangs..

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

  3. great blogs thanks i learned a few things

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

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

  7. you know. there is a syntaxhighlighter wordpress plugin ….

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

  9. Hello, thx for all,

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

  12. Excellent Dude, Thanks for sharing.

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

  14. [...] SendAndLoadExample: view plaincopy to [...]

  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. Храни себя от бед пока их нет

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

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

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

  20. Nice Post. Helped me a lot. Thanks

  21. Read more hot reports about Business, Form business or Women small business loans http://business.goodnano-av.com/

  22. 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. thanks a bunch!

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

  25. What happens if in the function

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

    the variable $code has the character “&”?

  26. amazing stuff thanx :)

    rH3uYcBX

  27. You are perfect!

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

    Thanks again!

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

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

    -Son
    http://www.sonsoftco.com
    New Web Design and Flash Games – SonSoft Company

  31. [...] [...]

  32. [...] [...]

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

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

  35. php code:

    $myName = ‘khaled’;

    print(‘name=’.$myName.’&age=five&height=34&weight=heavy’);

  36. LWDPL4 http://chfEd38MkKsw7cXv0x3Dlc3b7.com

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

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

    I am using linux.

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

  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”. http://bit.ly/uw1s4S You will be suprised how easy they are to fix.

  43. 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. it is very helpful thanks

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

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


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: