Flash sending, manipulating and receiving data with sendAndLoad
This is a very importat thing to know when you are about to design Flash forms, or any application that needs to manage data such as an highscore table.
This is a standalone tutorial, but the basics explained will be useful in the Creation of a Flash highscores API course.
The only method we need to know is sendAndLoad
Let’s dive into an example: I created an input text area called input_text, a button called send_button and a dynamic text called result_text.
Now, look at the code:
var php_process:LoadVars = new LoadVars();
send_button.onRelease = function() {
var post_variable:LoadVars = new LoadVars();
post_variable.string = input_text.text;
post_variable.sendAndLoad("http://emanueleferonato.com/downloads/sendtest.php",php_process,"POST");
};
php_process.onLoad = function(success:Boolean) {
if (success) {
result_text.text = php_process.result;
}
else {
result_text.text = "Error connecting to server.";
}
};
Line 1: Declaring a variable called php_process as LoadVars
The LoadVars class is useful for transferring variables between a Flash application and a server (who said “like an highscore”?)
Line 2: Beginning of the function to be executed when the send_button button has been pressed
Line 3: Declaring another LoadVars variable called post_variable
Line 4: Setting the string attribute of the post_variable as the content of the input_text dynamic text area
Line 5: Using sendAndLoad to pass post_variable to a script on the server at the address http://emanueleferonato.com/downloads/sendtest.php using the POST method and saving the result in the php_process variable
Line 7: Beginning of the function to be executed when the php_process has been loaded (when the server replied). Notice the success boolean flag
Lines 8-10: If success is true (I communicated with the server), then display in the result_test dynamic text area the result variable of php_process. We’ll see how to get the result variable when we’ll examine the php script
Lines 11-13: Dispaying an error if I wasn’t able to communicate with the server
Now, let’s see the php script in the
http://emanueleferonato.com/downloads/sendtest.php page
Line 3: If the string variable passed with POST method contains something…
Line 4: Convert the string to uppercase, just to do something…
Line 5: writing the content of the result variable as the uppercased value of the initial string
Lines 7-9: if the string variable passed with POST does not contain anything, then writing the content of the result variable as a message saying you did not write anything.
And that’s it… play with it and give me feedback
Write something in the upper text area and press “send”