Saturday, April 9, 2011

Flex With PHP connection using URL Loader

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
<mx:application layout="vertical" xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:script>
var variables:URLVariables = new URLVariables();
variables.UserName = "tushar";
variables.Password = "my_password";
mySendAndLoadExample.sendData(url, variables);
}
]]></mx:script>
<mx:button click="sendAndLoad()" label="Fetch data">
</mx:button></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.

Monday, October 19, 2009

comments in AS3

You can add comments to a script to describe the particular functionality of a block of code explain a problematic section of code, indicate where to start and end if editing of code at future dates, and so on.

There are two ways of commenting in ActionScript:
1) Single line-- Inserting two forward slashes (//) before a bit of code, will comment out the code for the rest of the line.
2) Multiline- Inserting a forward slash followed by an asterisk(/*) at the start of a block of code, and terminated by and asterisk and a forward slash(*/) at the end of the block of code, will comment out an entire block of code.

Ex:
Single Line comment:
// trace("This statement will NOT display in the output panel");
trace("This statement will display in the output panel");





Multiline comment:
/* trace("This statement will NOT
display in the output panel");
trace("This script is running");*/


comment.fla



We will see about the variables and properties in the next posts.

First Program using AS3

Using the trace() statement:

The trace() statement will become your best friend in ActionScript development. trace() statement helps to find the value for a variable at runtime. Much of the ActionScript functionality you will create does not have a visual result on the stage, so it can be difficult to tell if your ActionScript is doing its job properly in the background.
The trace() statement displays the results of your ActionScript as messages in the output panel at runtime.

To trace a value to the Output panel:

1. Create a new Flash file.
2. Select the first keyframe on Layer 1 and launch the Actions panel(f9).
3. Add the following ActionScript:
trace("the sum of 2+2 is :")
trace(2+2);
4. Press Ctrl+Enter(Win) or Cmd+Enter(Mac) to preview the results of your script.
5. The results of the script will be displayed in the Output panel.

trace.fla

The Language of ActionScript

Before we explore learning how to "speak" ActionScript, you need to learn the basic structure, format and aspects of the language.
Class and Objects
In object-oriented programming, classes and objects are the basis of all functionality. Objects on their own, however, are useless unless they are defined by a class. A class is the "blueprint" for an object's behavior, functionality, and characteristics.

In the context of ActionScript, a class is the equivalent of a blueprint. A class defines how an object is constructed(how it is introduced to the application); an object's properites; an object's methods; and how and object communicates(its event).

Classes are not stored in the Flash document itself, but in separate ActionScript files. They are imported into a script either automatically when a movie is compiled or by using import directive in your code.

An object is a copy of a class either in code or physically on the stage, or an instance of a class. If you construct more than one object of a class, you have multiple instances of a class.

Multiple objects of a single class can run autonomously from one another. Once an object of a class is instantiated, you can set its properties, call its methods, and listen and respond to its event.
Ex: var mc:MovieClip=new MocieClip();

Here we have created mc object for the class MovieClip. Using this object we can chance the object properties.
Ex: mc.x=100;
mc.y=100;


If u want to add the MovieClip into the stage, addChild(); function helps u.
Ex:
addChild(mc);
now the mc is added into the stage.
you can add the "mc" to any other object that name is "man". U use the syntax:
Ex: man.addChild(mc);

Intro AS3

ActionScript is an exciting scripting language for creating applications for the Web,desktop, and personal devices. It's unique compared to many languages in that it is not strictly a data exchange language. It is capable of generating interactive, rich media-driven applications, complete with design, animations, sound and video.

Action Script 3 is a full-fledged object oriented programming language. Compared to the previous version, it offers improved event handling, a new display list, and a drawing API. In addition, overall performance has drastically increased, making the latest version definitely worth a try.