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.


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 “&”?


Leave a response

Your response:

Categories