Tuan Anh's Blog

How to become stronger

Using URLLoader to send and load server variables

Posted by tuananh108 on March 11, 2009

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:

  1. package {
  2. import flash.events.*
  3. import flash.net.*;
  4. public class SendAndLoadExample {
  5. public function SendAndLoadExample() {}
  6. public function sendData(url:String, _vars:URLVariables):void {
  7. var request:URLRequest = new URLRequest(url);
  8. var loader:URLLoader = new URLLoader();
  9. loader.dataFormat = URLLoaderDataFormat.VARIABLES;
  10. request.data = _vars;
  11. request.method = URLRequestMethod.POST;
  12. loader.addEventListener(Event.COMPLETE, handleComplete);
  13. loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
  14. loader.load(request);
  15. }
  16. private function handleComplete(event:Event):void {
  17. var loader:URLLoader = URLLoader(event.target);
  18. trace(“Par: ” + loader.data.par);
  19. trace(“Message: ” + loader.data.msg);
  20. }
  21. private function onIOError(event:IOErrorEvent):void {
  22. trace(“Error loading URL.”);
  23. }
  24. }
  25. }

Now, create an object of SendAndLoadExample class in Flex.

SendAndLoadExample.mxml

  1. <?xml version=“1.0″ encoding=“utf-8″?>
  2. <mx:Application xmlns:mx=“http://www.adobe.com/2006/mxml”
  3. layout=“vertical”>
  4. <mx:Script>
  5. <![CDATA[
  6. import flash.net.URLVariables;
  7. private var mySendAndLoadExample:SendAndLoadExample;
  8. mySendAndLoadExample = new SendAndLoadExample();
  9. private function sendAndLoad():void {
  10. var url:String = "http://[your server]/login.php”;
  11. var variables:URLVariables = new URLVariables();
  12. variables.UserName = ”tushar”;
  13. variables.Password = ”my_password”;
  14. mySendAndLoadExample.sendData(url, variables);
  15. }
  16. ]]>
  17. </mx:Script>
  18. <mx:Button label=“Fetch data” click=“sendAndLoad()”/>
  19. </mx:Application>

PHP Script for login check: login.php

  1. <?
  2. $clientUserName=$_POST['UserName'];
  3. $clientPassword=$_POST['Password'];
  4. //////////////////////////////////////
  5. // Host name
  6. $host=“[your server]“;
  7. // Mysql username
  8. $username=“[MySql database username]“;
  9. // Mysql password
  10. $password=“[MySql database password]“;
  11. // Database name
  12. $db_name=“[MySql database name]“;
  13. // Table name
  14. $tbl_name=“[MySql table name having usernames and passwords]“;
  15. function makeConnection() {
  16. // Connect to server and select databse.
  17. mysql_connect(“$GLOBALS[host]“, “$GLOBALS[username]“,
  18. “$GLOBALS[password]“)or die(“cannot connect”);
  19. mysql_select_db(“$GLOBALS[db_name]“)or die(“cannot select DB”);
  20. }
  21. function fireQuery($query) {
  22. $result=mysql_query($query);
  23. return $result;
  24. }
  25. function printOutput($code, $msg){
  26. print “par=$code&msg=$msg”;
  27. }
  28. //////////////////////////////////////
  29. function checkUserID($id, $password) {
  30. $sql=”SELECT * FROM $GLOBALS[tbl_name] WHERE
  31. userName=‘$id’ and password=‘$password’“;
  32. $result=fireQuery($sql);
  33. $count=mysql_num_rows($result);
  34. if($count==1){
  35. return true;
  36. }
  37. return false;
  38. }
  39. function init(){
  40. if(isSet($GLOBALS["clientUserName"])
  41. && isSet($GLOBALS["clientPassword"])){
  42. makeConnection();
  43. if(checkUserID($GLOBALS["clientUserName"]
  44. $GLOBALS["clientPassword"])){
  45. printOutput(“1″, “Login successful.”);
  46. else {
  47. printOutput(“0″, “Failed to login $GLOBALS[clientUserName].”);
  48. }
  49. else {
  50. printOutput(“0″, “Required parameters missing.”);
  51. }
  52. }
  53. init();
  54. ?>

However, you can also use HTTPService to send and load data in Flex. Nitin has posted a simple example of using HTTPService in flex.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>