ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
SharedObject Applications
http://www.actionscript.org/resources/articles/190/1/SharedObject-Applications/Page1.html
Hasan Otuome
Hasan Otuome is Chief Architect for Marx Media (http://www.marxmedia.net) where he can usually be found developing Rich Internet Applications for the company's clients. He champions creative uses and combinations of Flash, PHP, AJAX and MySQL, among others, for their benefits in user experience improvement. 
By Hasan Otuome
Published on February 23, 2006
 
Tutorial details:
Written by:
Hasan Otuome
Time: 30mins - 1 hr
Difficulty: Advanced
Requirements: Flash 8
Topics Covered: Using SharedObjects and LoadVars.
Assumed knowledge: Actionscript. SharedObject, LoadVars, arrays and for loops.

You can grab the tutorial files here

In this tutorial I'll show you creative uses of Flash's SharedObject to meet your clients increasing demands.

The Concept
As you grow as a developer you will undoubtedly be asked to develop more intensive Flash applications. One such application could be a multi-page form. Here's the scenario: your client wants to be able to collect detailed user data and the client wants it to be as painless as possible to the user. Translation: the form needs to maintain state so that the user doesn't have to re-enter all that detailed info in case a connection is lost, a computer crashes or the user chooses to start now and finish later. And of course, the client wants to receive all that data once the user has completed the process. Now while there are several ways you could accomplish this, I want to focus on making use of Flash's SharedObject.

If that's your first time hearing that term, my good buddy, Jesse Stratford, has written an excellent tutorial that lays the groundwork for what we're about to cover here. Click here to read Jesse's tutorial.

Now, what we are going to do is take advantage of the power that Flash lays at our feet by using a SharedObject to maintain state and a couple of LoadVars to handle data transmissions. First thing we want to do before even opening Flash is to map out the requirements and all the data we'll need to collect. By doing this it will decrease the amount of time to code because we'll have a handy desktop reference to look at while coding. For example you could make a chart like:

Data Type    Flash Variable  PHP/JSP/ASP Variable
text               firstname         fname
etc...

Once that's done we're ready to head over to Flash.

The Basics
First thing we want to do after setting up our layers is to add some code to our actions layer that will come in handy as the application takes shape. So with your actions layer selected and your actions panel pulled up, add the following:

[as]
_global.root = this;
_global.cookie = SharedObject.getLocal("objectnamehere");


function KillIt(){
    for (var i in cookie.data){
        delete cookie.data[i];
    }
    cookie.flush();
}
[/as]

As you can see, we've created (2) _global variables: a reference to the main timeline of this application's _root and a reference to the SharedObject we're creating (if it doesn't exist) or loading (if it does). We also defined a function that we will call at the end of the process that will destroy the SharedObject. Now, this approach will definitely come in handy if you decide to use movie clips for each of the form's pages.

With that out of the way we can add code to the actions layers of each of our page clips. Here we can make use of that organization chart, b/k/a "cheat sheet", we created earlier. We've already completed the layout of the pages and given instance names to all of the page's components (if using them) or our text fields. So now we can add code to the actions layer that will collect the user data entered on this "page" and store it in our SharedObject. We could code it like this:

[as]
cookie.data.var1 = var1.text;
cookie.data.var2 = var2.text;
cookie.data.var3 = var3.text;
cookie.data.var4 = var4.text;
etc,etc...
cookie.flush();
[/as]

And that would definitely store the info. But, what if this page had (30) variables to collect? That's right, it would become tedious to either type line after line or copy/paste line after line. So how can we make it more efficient?
We'll see on the following page...

Efficiency Anyone?
One way to make this process more efficient is to make use of an array and a for..next loop. With our trusty cheat sheet handy we're going to modify the code above by first creating an array of all our instances and then looping through the array to do our "key" = "value" assignments. Here's what I mean:

[as]
var i:Number;
var tl = this;
var uData:Array = ["var1","var2","var3","var4"];

for (i=0; i<uData.length; i++){
    cookie.data[uData[i]] = tl[uData[i]].text;
}
cookie.flush();
[/as]

So instead of taking 30+ lines of code we accomplish the same thing in 8. Now which one do you think would be easier to troubleshoot if something went wrong? My bet's on the 8-liner. And it also gives us a reusable framework that we can apply to the other "pages" only having to modify the array. This will seriously reduce our develop time and decrease our margin of error. Now that you've got the general idea we can skip over to the end of the app and deal with prepping the data for it's POST-Flash journey.

Ok, the user has made it to the end of the app and has successfully passed all of our validation routines. Now we need to send this data to the client by the required means. Maybe the client wanted the data input into a database or sent via email or both. Whichever was chosen, we'll make use of Flash's LoadVars to handle the task. Remember, we've been collecting pages and pages of data which has more than likely grown quite massive. Therefore, it would be a daunting task to create our LoadVars were it not for our handy looping techniques. Oh yes, we're going to employ the same concept we used on each of the pages to store the data to our SharedObject. Here we're just creating a loop that will build our LoadVars from the data stored in the SharedObject. But before we do that we'll create our LoadVars and messages to display to the user based on what kind of response we receive from our processing script (ASP,JSP,PHP...).

[as]
var sender:LoadVars = new LoadVars();
var receiver:LoadVars = new LoadVars();

var successMsg:String = "Data Transmission Successful";
var failureMsg:String = "Data Transmission Failed";
[/as]

Now we want to create the loop that will build our LoadVars, "sender" with the data from our SharedObject, "cookie" and decide which message to display to the user when our processing script responds to us:

[as]
for (i in cookie.data){
    sender[i] = cookie.data[i];
    sender.sendAndLoad("processor.php",receiver,"POST");
}

receiver.onLoad = function(){
    if (this.sent){
        msgBox.text = successMsg;
        root.KillIt();
    } else {
        msgBox.text = failureMsg;
    }
}
[/as]

So what we've done is added all the data from our SharedObject to our LoadVars and sent that to our processing script. Our processing script will process all the data and, if successful, will return a variable that our other LoadVars can check for and based on that will display the appropriate message to the user. This approach definitely saved me on a recent project where one of the apps contained over 280 variables! Without looping functionality I'd still be coding right now :) Enjoy!

Hasan
hasan at marxmedia dot net