Section 13.2. Sending Results with a Form


13.2. Sending Results with a Form

Now that you have a working quiz, it would be great if your students could send their results to their instructors. This requires not only a little setup in your Flash file (commonly referred to as the client-side portion of the solution), but also a server script to send the submitted data via email.

Server scripting is beyond the scope of this book, but a basic PHP example that you can adapt to your needs has been provided so that you can more easily understand it. PHP (which originally stood for Personal Home Page but has become known as a recursive form of Hypertext Pre-Processor) is a powerful yet simple server scripting language supported by the vast majority of Internet service providers.

For the purposes of this project, a few user-configurable lines in the PHP script will be discussed, but you shouldn't have to change much beyond that.

13.2.1. Creating a Form

Before you get to the server script, you need to create a form that will send the user data to the server. In this project you'll take advantage of what you learned in the previous chapter to load a flexible, reusable form into your quiz. This makes it possible to use the same form in multiple projects. Remember, the more modularized you can make your content, the more you will get out of it.


Note: The setup of the form .fla will be detailed in the following steps, but if you prefer, you can open form_01.fla from the 13 folder of your working directory. In this file, the fields and buttons have been created and instance names have been provided, but no scripts have been included. This will save you a bit of time in asset creation but still allow you to add the scripts yourself for practice.

Here are the steps involved in creating the form:

  1. Create a new file and save it as form.fla in your 13 folder. In the Modify Document dialog, give it dimensions of 320 X 330.

  2. Start by creating the first field. (You will then repeat this process for the remaining fields.)

  3. Select the Text tool and draw a text field on the Stage. Convert the text element to an input text field, and give it an instance name of sname_txt (which stands for a text field for sender name). To keep file size down, choose the _sans device font for the field's contents.

  4. Grab one of the great new text element corners (introduced in Flash 8) to resize the text field to approximately 220 X 20 pixels. Move the field on Stage to approximately (78, 20).

  5. Finally, create a static text element to serve as a descriptive label next to the field. Add the text Sender Name.

  6. As an added interface nicety, switch to the background layer and use the Rectangle tool to draw a tinted box below the field and text label.

  7. Repeat steps 4 through 7 four more times, using the information shown in Table 13-1.

    Table 13-1. Specifications for text fields 25

    Text label

    Instance name

    Size

    Location

    Sender Email

    semail_txt

    220 X 20

    (78, 45)

    Recipient Email

    remail_txt

    220 X 20

    (78, 90)

    Subject

    subj_txt

    220 X 20

    (78, 130)

    Message

    msg_txt

    220 X 60

    (78, 160)



    Note: These sizes and locations are just approximations to make the creation process a bit easier. Feel free to adjust the values as you go. The values used in the provided source files also differ within a few pixels.

  8. For the last input box, create a sixth text field with no label. Make it a dynamic text element (instead of input, like the previous fields) and give it an instance name of status_txt. Size it to 300 X 60 pixels, and place it at (10, 260). As a last step, in the Properties panel, disable the selectable option for this field, indicated by the cursor in Figure 13-6.

    This will prevent the user from editing the status that your form will report for each process.

    Figure 13-6. Disable the selectable property for the status field to prevent user editing at runtime

  9. Finally, in the form layer, create a little close button in the upper-right corner and give it an instance name of close_btn.

When you're done, save your work and compare your file with form_01.fla, seen below in Figure 13-7. You'll start adding buttons in the next step, but notice how the background tints group functionality together and improve the readability of the form. If you want to make any adjustments, do so now and then continue.

13.2.2. Adding buttons

Now it's time to add the buttons to manipulate the form:

  1. Open the Components panel and drag the Button component to the Stage. (It's found in the User Interface components category.)


    Note: This is just a tutorial step to speed up the process by eliminating the need to create your own custom button. If you are concerned about the file size this component adds, or you want to customize your form's appearance, feel free to create your own button.

  2. With the button selected on the Stage, show the Parameters tab in the Properties panel. Change the Label parameter to Submit. Give this button an instance name of submit_btn.

  3. Make a copy of this button and change its Label parameter to Clear. Give this button an instance name of clear_btn.

The bulk of your form should now be done. You will add more buttons later, but your existing buttons should resemble those seen in the completed form in Figure 13-7. All you need to do now is add ActionScript that compiles the data from the form and sends it to the web server.

Figure 13-7. The completed form


13.2.3. Compiling and Sending Form Data

Once the user fills out the email information, the data must be sent to the web server for processing. As stated earlier, server-side scripting is beyond the scope of this book, but a complete basic PHP script has been included in the 13 folder on the book's CD-ROM.

In this part of the project, you'll compile and send the form data:

  1. In frame 1 of the actions layer, start with a script that creates a LoadVars object to receive any response from the server. A simple button event handler will do:

     submit_btn.onRelease = function():Void {     var eResponse_lv:LoadVars = new LoadVars(); }; 

    The LoadVars class makes it easy to send information to, and receive information from, a server. For more information, see the "Loading and Sending Variables" sidebar.

    Loading and Sending Variables

    There are a few ways to load data from an external source (such as a text file or web server), and similar ways to send the data. One method that you will likely be familiar with is simulating a standard web form and loading or sending standard name/value pairs. Name/value pairs are named as they are because a variable's name and value are loaded or sent as a pair, either in a URL or in an object.

    After submitting a web form or clicking on a link, you may have seen a URL that looked something like this: http://www.domain.com/script.php?user=brian.

    This demonstrates the transmission of a variable called user and its value, brian, to a server script. Just like a web form, name/value pairs can be loaded or sent using the GET method, which adds data to a URL (as seen above), or the POST method, which sends the data in a hidden object.

    Flash makes this process easy using the LoadVars class and its sendAndLoad() method. Using this class and method, you can specify GET or POST, send data, and load any result from the server.

    The process requires a few simple steps: 1) create a sending LoadVars object to send your variables from; 2) create a receiving LoadVars object to receive any feedback from the server; 3) create an event handler to wait for the server response; and d) send the data. Here is an example script:

     var mySend_lv:LoadVars = new LoadVars(); var myReceive_lv:LoadVars = new LoadVars(); myReceive_lv.onLoad = function():Void {     trace(myReceive_lv.scriptStatus); }; mySend_lv.user = "brian"; mySend_lv.sendAndLoad("http://www.domain.com/script. php",myRecieve_lv, "POST"); 

    The onLoad event handler is required because Internet operations are asynchronous. That is, they are not immediately sequential. For example, if you executed the trace line immediately after sending the data to the server, there would be no time for the data to be sent, for the server to process the request, or for the server to respond. The event handler effectively means, when a response is received, process it. Using this approach, you don't have to wait around for the server to respond.

    You can also improve this example script by adding error checking for the server response. The LoadVars example in this chapter takes this extra step.


  2. Add to the end of the same object an onLoad event handler to capture any server response. Update the status_txt field with text from the scriptStatus variable that is defined in the script:

     eResponse_lv.onLoad = function(success):Void {     if (success) {         status_txt.text = "Transmission successful.\n";         status_txt.text += this.scriptStatus;     } else {         status_txt.text = "An error occured.\n";         status_txt.text += this.scriptStatus;     } }; 

  3. Add to the end of the same onRelease event handler a new LoadVars object to send the data. Create properties of the object to contain the variable data:

     var eMail_lv:LoadVars = new LoadVars(); eMail_lv.sname = sname_txt.text; eMail_lv.semail = semail_txt.text; eMail_lv.remail = remail_txt.text; eMail_lv.subj = subj_txt.text; eMail_lv.msg = msg_txt.text; 

  4. Use the same object to send the data and load any response from the server. Use the correct pathname to your version of the PHP script in the first parameter:

     eMail_lv.sendAndLoad("flash8projects_email.php", eResponse_lv, "POST"); 

    Note the use of the receiving LoadVars object in the second parameter to catch the response, and notice the use of the POST method. The POST method is usually superior to the GET method because it can send more information and the overall syntax is simpler.

    Finally, program three user interface enhancements:

  5. First, add as the first line of the onRelease handler an instruction that clears the status field each time you submit data. This makes any new server feedback more obvious:

     status_txt.text = ""; 

  6. Second, make it possible to clear all fields with a form reset button:

     clear_btn.onRelease = function():Void {     status_txt.text = "";     semail_txt.text = "";     remail_txt.text = "";     subj_txt.text = "";     msg_txt.text = ""; }; 

  7. Third, script the close button to unload this form (remember, you've designed this form to be loaded into another SWF):

     close_btn.onRelease = function():Void {         this._parent.unloadMovie(); }; 

    If you need a refresher on the this and _parent keywords, see the "Absolute and Relative Target Paths" sidebar in Chapter 6.

  8. Your script, so far, should look like this:

     //send   form contents to php script for emailing submit_btn.onRelease = function():Void {      status_txt.text = "";      var eResponse_lv:LoadVars = new LoadVars();      var eMail_lv:LoadVars = new LoadVars();      eMail_lv.sname = sname_txt.text;      eMail_lv.semail = semail_txt.text;      eMail_lv.remail = remail_txt.text;      eMail_lv.subj = subj_txt.text;      eMail_lv.msg = msg_txt.text;      eMail_lv.sendAndLoad("flash8projects_email.php", eResponse_lv,"POST");     eResponse_lv.onLoad = function(success):Void {         if (success) {              status_txt.text = "Transmission successful.\n";              status_txt.text += this.scriptStatus;         } else {              status_txt.text = "An error occured.\n";              status_txt.text += this.scriptStatus;         }     };  };  //clear all form fields except name. local shared object not  affected  clear_btn.onRelease = function():Void {     status_txt.text = "";     semail_txt.text = "";     remail_txt.text = "";     subj_txt.text = "";     msg_txt.text = ""; }; //unload this form close_btn.onRelease = function():Void {     this._parent.unloadMovie(); } 

To test your movie at this point, you'll need to have access to a server with PHP enabled. If you don't have access to such a setup, you can compare your file with form_02.fla.

13.2.4. Server Script Parameters

Although covering server scripting is outside the scope of this text, it will help you adapt the sample script (provided on the CD-ROM) to your needs if you understand three simple parameters.

These parameters can be found at the top of the script, and appear as follows:

 //****************************  //start customizable variables  $subject = "Demo: Flash 8 Projects for Learning Animation and  Interactivity";  $success_string = "Email sent by   server on "; //followed  immediately by date  $failure_string = "Email could not be sent. Check for valid  recipient email address and message.";  //end customizable variables  //**************************** 

The first is the default subject for the email to be sent. This is used only if the user does not fill in a subject of his or her own. You can change this to any valid subject, or remove the text (leaving the two quotation marks) if you want the subject to be blank, the way the user may have intended.

The second is the success string sent back to Flash. If you modify this, remember that the date immediately follows this string. That's why a trailing space is included in the provided context.


Note: Remember, semicolons are required at the end of every line in PHP.

The third parameter is the failure string sent back to Flash. Since the email fails to send on the server side for only two reasons, you can include helpful text to let the user know what to look for.

As you get better at ActionScript, you can perform what is called client-side validation to try to catch as many errors as possible before even submitting to the server. In any case, it's still a good idea to perform error checking at the server, as well.



Flash 8(c) Projects for Learning Animation and Interactivity
Flash 8: Projects for Learning Animation and Interactivity (OReilly Digital Studio)
ISBN: 0596102232
EAN: 2147483647
Year: 2006
Pages: 117

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net