Introduction
The LoadVars class allows developers to have a better control of the external loaded data. There are many reason to use the LoadVars class intead of the old deprecated loadvariables and loadvariablesNum
Brief Description of LoadVars
Both LoadVars and loadvariables allow flash to communicate with external data source, but LoadVars offers methods, being a class, which the loadvariables doesn't support, being a global function.
Some of the benefits if the LoadVars:
1) availability of internal methods, in order to control the received/sent data, such as onLoad. the onLoad method is executed automatically (this means you don't need to make a call) once data is received from flash. Moreover the same onLoad method has an internal argument which tell us if data has been received or not (Example of a 404 page)
2) methods such as getBytesLoaded and getBytesTotal. We can know how much data we are loading.
3) all the data sent or received from the LoadVars class remains into the class itself. This is a big differences between the loadvariables function in which all the data received were stored in the same scope of the function (thus overwriting all the data in the same level). This offers again a better control on the data received
1. the .load() method
Description:
the LoadVars.load() method loads variables from an external source in URL-encoded format. Flash will read the output of the page you're loading. Once all the data is loaded, all the variables will be stored into the LoadVars instance which makes the call.
Example of url-encoded output (the only which flash can read using loadvars):
nome=pietro&nick=lana&mail=pietro@flash-php.it
for more info about the format at macromedia.com
Returns:
- a boolean value into the onLoad handler, which means if data has been received correctly.
Usage:
A simple usage.
Let's create a simple php page like this:
$nome = "pietro" ;
$nick = "lana" ;
$mail = "pietro@flash-php.it" ;
/*
print the variables to the output in order to let flash read them
*/
$vars = "" ;
$vars .= "nome=" . $nome . "&" ;
$vars .= "nick=" . $nick . "&" ;
$vars .= "mail=" . $mail ;
echo $vars ;
?>
Note the usage of "&". if you have more than 1 variable to send to flash you must concatenate the variables with the "&" (like the urlencoding using the GET method in html). Each time flash will read the & char it will assume that the following word it's a variable name.
name=pietro&nick=lana
will prduce in flash:
name = "pietro";
nick = "lana";
If you need to use the "&" char inside a variable text (for example name=Alex&me) you must urlencode the "&" value into %26 (name=Alex%26me)
To lad variables in flash:
/* first create a new instance of the LoadVars object */
myVars = new LoadVars();
// call the load method to load my php page
myVars.load(" http://percorso/pagina.php ");
// once vars have been loaded, we will have these variables:
myVars.nome // "pietro"
myVars.nick // "lana"
myVars.mail // "pietro@flash-php.it"
Note:
- every variable received will be a string, this means that if you pass [ value=1 ] , once received we will have this:
myVars.value = "1;
- PAY attention of spaces before of after your code, it will be read!
for example if you write into a .txt file:
name=alex
&value=20
&num=1
you'll have in flash:
myVars.name = "alex\r\n";
myVars.value = "20\r\n";
myVars.num = "1";
Another important consideration.
When working with php files, if you make a .load calls in flash like this:
myVars.load("file.php");
you can't test your movie inside the flash IDE (CTRL+ENTER), this because in this way the php file won't be processed from your webserver and flash will read the source code of the php file, not the expected output!!
For this reason, while you're testing your movie inside the flash ide, use always absolute paths:
myVars.load("http://localhost/file.php");
where localhost is just an example, it can be your domain name
( this is a common error )
2. the .onLoad method
When all the variables has been loaded and parsed by the LoadVars object, the onLoad method is executed, if defined.
Let's use a simple trace action to see if our variables has been loaded..
myVars.onLoad = function( ){
trace("variables loaded");
}
An important thing to know is that the onLoad method is invoked from the onData method (another method of the LoadVars object) in this way:
this.onLoad(success);
As you can see it will pass the "success" parameter, a boolean (true/false) which means if the page is loaded correctly or not.
So, our code will be:
myVars.onLoad = function( success ){
if(success){
trace("variables loaded");
} else {
trace("Error loading page");
}
}
Now we can see how to access to the loaded variables.
myVars.onLoad = function (success) {
if (success) {
trace (" variables loaded ");
for( var prop in this ) {
trace (" key " + prop + " = " + this[prop]);
}
} else {
trace (" Error loading variables ");
}
}
Note the usage of "this" inside the myVars onLoad method. In fact while the onLoad method is executing everytime we use "this" we are refers to the myVars object itself, not the flash timeline !
All the variables are stored into the myVars object, so for this reason we need to use "this" to access to them.
But, if you want to access to the current timeline?
In order to refer to the timeline in which the onLoad methos is working you can do this:
myVars._path = this /* we are outside the onLoad method, to "this" is the current timeline */
myVars.onLoad = function (success) {
trace(this._path) // will output "_level0"
if (success) {
trace (" variables loaded ");
for( var prop in this ) {
trace (" key " + prop + " = " + this[prop]);
}
} else {
trace (" Error loading variables ");
}
}
Note:
a common error is try to access to the LoadVars properties when they are not already loaded. You can only access to its property only after the onLoad handler is executed, not before!
Example of wrong usage:
myVars._path = this;
myVars.onLoad = function(){
this._path.name = this.name
}
trace(myVars.name) // ERROR!!
correct usage:
myVars._path = this;
myVars.onLoad = function(){
this._path.name = this.name
trace(myVars.name) // CORRECT
}
3. method onData()
Description:
onData is automatically executed once external data is received, but not already parsed into property of the LoadVars object.
By default it is something similar to this:
LoadVarsObj.onData = function(stringa) {
if (stringa == undefined ) {
this.onLoad(false );
} else {
this.decode(stringa);
this.onLoad ( true );
}
}
For this reason it will pass to the onLoad method tha value true or false depending on the content of the data received, if no data has been recived this value will be false.
The decode method parse the url-encoded variables into readable property by flash.
You can overwrite this method with your own functions, but pay attention what you're doing.
4. send() method
Description:
send is used when you want to send some variables to an external page. It automatically converts the property of the LoadVars object into a url-encoded string
Returns:
Return always a true value, if the LoadVars object has at least one property to send, otherwise it returns false
Usage:
If we have a php page with a mysql query which expects nome, nickname and email as external variables:
if(!empty($_POST['nome']) && !empty($_POST['nick']) && !empty($_POST['mail']))
{
$conn = mysql_connect('host', 'user', 'pass') or die(mysql_error());
$db = mysql_select_db('db_name', $conn) or die (mysql_error());
$nome = $_POST['nome'];
$nick = $_POST['nick'];
$mail = $_POST['mail'];
$result = mysql_query("INSERT INTO nome_tabelle (nome, nick, mail)
VALUES ('$nome', '$nick', '$mail')") or die(mysql_error());
if($result)
{
echo "Everything is ok";
} else {
echo "Error writing data";
}
mysql_close($conn);
}
?>
In flash: first create a new instance of the LoadVars object, then assign to it all the properties to pass, and finally call the send method.
myVars = new LoadVars();
myVars.nome = "pietro";
myVars.nick = "lana";
myVars.mail = "pietro@flash-php.it";
myVars.send("http://localhost/pagina.php", "_blank", "POST");
the argument "_blank" tell flash in which target open the destination page "pagina.php". _blank means that a new page will be opened.
In the php page the variables are readed from the superglobal array $_POST, so we need to pass the variables using the method "POST", which is the 3rd argument passed n the send method.
5. sendAndLoad()
Description:
sendandLoad method combine the functionality of the methods load() and send(), it parse the properties of the LoadVars object in url-encode strings and send all to the external page, and will read the result output which this page send back as response.
We can specify which LoadVars object has to receive response. In most cases, use the same instance both for send and read data.
yVars = new LoadVars();
myVars.SendAndLoad(" http://percorso/pagina.php ", myVars, " POST ");
the arguments: page url, receiver object, sending method
Returns:
the same as the send method.
Usage:
For this example we will authenticate a user which send his login name and password from flash
This is the php page which check the login and password reading a db:
if(!empty($_POST['nick']) && !empty($_POST['password']))
{
$conn = mysql_connect('host', 'user', 'pass') or die(mysql_error());
$db = mysql_select_db('db_name', $conn) or die (mysql_error());
$nick = $_POST['nick'];
$pass = $_POST['password'];
$result = mysql_query("SELECT * FROM tabella_utenti
WHERE nick= '$nick' AND password = '$pass'") or die(mysql_error());
$num = mysql_num_rows($result);
if(num >0 )
{
echo "login=true&";
echo "msg=you're logged now";
} else {
echo "login=false&";
echo "msg=wrong user name or password";
}
mysql_close($conn);
} else {
echo "login=false&";
echo "msg=missing data";
}
?>
In flash we will have 2 input textfield with instance name "nickname" and "password",
flash form
and in the same level a button with this code:
on(release){
myVars = new LoadVars();
myVars.nick = nickname.text;
myVars.password = password.text;
myVars.onLoad = function(success){
if(success){
trace(this.msg);
if(this.login){
// ok, you're logged.. go to the page for
// registered users
}
} else {
trace("Error reading the php page");
}
}
myVars.SendAndLoad("http://percorso/pagina.php", myVars, "POST");
}
6. Other methods
The LoadVars object has also other methods:
.toString()
It will transoform all the properties of the LoadVars object into a string url-encoded. It is used by default from the send, sendAndLoad methods.
.decode()
It's the inverse method.. from an url-encoded string return well formatted properties.
.getBytesLoaded() & getBytesTotal()
Same usage as the getBytesLoaded() and getBytesTotal() from the MovieClip class. they return the bytes from an external loaded source.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment