Nov 8, 2009

Submitting A Form In Flex (follow Up Of Sm's Tut)

free web hosting
Open Discussion > MODERATED AREA > Tutorials

Submitting A Form In Flex (follow Up Of Sm's Tut)

shadowx
Now Saint Michael made an excellent 3 part tutorial that explains how to make a form HERE So if you need to design a form follow his nice tutorial. He did however mention he didnt know (yet) how to submit a form, so i did some searching last night and made my form submit to a PHP file and this is how its done (roughly, ive only had flex since last night so expect problems!

My form is designed as an email contact form but at the moment because i dont have a local mail server configured im using the fwrite functions in PHP to illustrate that it works and to save the values of the variables to a text file to prove they are working, if it comes to rolling it out then i can use the mail function just by editting the PHP.


CODE
<mx:HTTPService
        id="sendmycontact"
        url="contact.php"
        result="resulthandler(event)"
        resultFormat="text"
        method="POST"

    >


First of course there is the HTTPService tag. Basically similar (as far as i can tell) to the <form> HTML tag. You specify the URL which is the "action" of a <form> and then of course the method, POST, GET and others i cant remember! all you need for a very basic form is the URL and the action parts and of course the ID which is used later to submit it. The interesting part is the "result" property. This is a property that defines what to do if/when the form receives an answer from the script, in my example i used the php: or die("failed") to provide feedback to the flex form. It automatically receives the text "failed" if the PHP encounters an error (for example your mail server dies and your user thinks a message has been sent but it hasnt. The error handler will notify the user of an error). In my example i created a function that i will explain in a sec, that takes the value of 'event' which will contain the text from my php file. So if my PHP die statement was: or die("no luck"); then the resulthandler(event) would pass on the value "no luck" to my function. You also need to specify the format of the result. In this case it is text. You can also use XML feedback for moe complex things like database functions. Anyway....

The next part is this:

CODE
<mx:request xmlns="">
            <name>{fname.text}</name>
            <email>{email.text}</email>
            <message>{message.text}</message>
        </mx:request>
    </mx:HTTPService>


This basically sets the data to be transmitted to the URL specified in the first code block. In my example i have the users name, email address and their message. Basically my PHP code receives a variable named "name" containing the data from the fname text input box (this is set by the code: {fname.text} ) Now as you notice this code comes WITHIN the mx:HTTPService tag which is now ended after the mx:request tag. AS far as i know the xmlns property doesnt need to be filled in. I may be wrong but it works so far!

Now we need to define our functions that submit the form and process the feedback.

firstly you need (it seems) to import the controls form the library inside the mx:Script tag:

CODE
<mx:Script>
        <![CDATA[

            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.controls.Alert;


You can see the Result and Fault Events have been included here as has the Alert controls because we will use an Alert to advise the user. Now we need to create our function to submit the form to the PHP program. I have called my function "sendmyemail" you can call it what you want. Youll notice i have also used the ID i set for my HTTPService which is "sendmycontact" (If you are confused see the first code block)

CODE
function sendmyemail():void
        {
        sendmycontact.send();
                
        sendmycontact.resultFormat = "string";
        sendmycontact.addEventListener(ResultEvent.RESULT, resulthandler);
        sendmycontact.addEventListener(FaultEvent.FAULT, fault_handler);
    }


Im not sure why we have the ":void" after the function declaration... But its a fact of life! It seems to replace "functionname(void)" in other languages (i have very little experience of actionscript and OO JS). EDIT: I have just discovered the meaning of the :void. It is the declaration of the type (eg string, int) that the program can expect. So as the program is going to receive a NULL value (void) the variable "type" is void, and the way to write that is :void an integer return would be :int and so on smile.gif. The part that submits the form is the "sendmycontact.send();" statement. So now the form is sent. If you dont want to provide feedback on errors or success then that is the only line you need. However i will continue! Again we declare the format of the result expected from PHP You now see we are adding EventListeners to our HTTPservice, one to listen for a positive result, and one to listen for an error known by flex as a FAULT. First you tell flex you wish to add a listener with sendmycontact.addEventListener now you tell it to listen for a result/fault event with "(ResultEvent.RESULT," (substitute result for fault of course for a fault report) and then we name that listener as "resulthandler" or "fault_handler" respectively. Any names can be used here. So now the form has been submitted and flex is eagerly listening to the PHP for any sort of output. When it receives that output it will be put into resulthandler(event) as the <mx:HTTPService> Tag defined. So now we need to create this function using the following code:
CODE
function resulthandler(event):void{
            if(event.result == "failed")
            {
            fault_handler();
            }
             else
             {
                Alert.show("Thanks! Your comments have been emailed and we will reply shortly if required.", "Thanks!");
            }
            }


So we take the value of "event" given to use by the HTTPService tag which is of course the output from PHP. (again im not sure why the :void is there but it seems to work! Feel free to correct my codes, ive only been learning flex for about 18 hours!) Now For some reason we must use the "event.result" variable/property of the event which contains the actual PHP output. In my PHP i wrote or die("failed") so in the event of some error my PHP output is simply the word failed so my IF statement logically checks to see i the output was "failed" If it was then there was of course an error and i need to notify my user and i do so using the fault_handler() function explained in a sec. The else statement of course is there in the event that the output is NOT the word failed (hence the PHP succeeded and the email was sent) then we can tell the user the email was sent using that alert box there. The first string is the message displayed and the second, shorter string, is the text of the alert box's title bar. So the user is greeted with a message saying they have done their part and can wait for the reply or whatever.

CODE
function fault_handler():void{
                Alert.show("The operation failed. Your comments were not received due to a technical failure. Please try again later after we have fixed this problem", "Failed");
        }


This is the opposite function that simply gives an alert telling the user it failed and to try again later.

And that my friends is that! Of course to trigger this lot off you need to use: click"sendmyemail()" in your submit button.

As i said ive only been learning flex since last night so this isny fool proof and its not very neat. But it gives you a nice starting point. What i would really like to find out is how to prevent my form being submitted if my validation (see SM's tut) flags up an error. Im working on that now!! But if you know an easy solution to that then reply and let me know biggrin.gif

 

 

 


Comment/Reply (w/o sign-up)

Saint_Michael
QUOTE

Now Saint Michael made an excellent 3 part tutorial that explains how to make a form HERE So if you need to design a form follow his nice tutorial. He did however mention he didnt know (yet) how to submit a form, so i did some searching last night and made my form submit to a PHP file and this is how its done (roughly, ive only had flex since last night so expect problems!

My form is designed as an email contact form but at the moment because i dont have a local mail server configured im using the fwrite functions in PHP to illustrate that it works and to save the values of the variables to a text file to prove they are working, if it comes to rolling it out then i can use the mail function just by editting the PHP.
CODE
<mx:HTTPService
        id="sendmycontact"
        url="contact.php"
        result="resulthandler(event)"
        resultFormat="text"
        method="POST"

    >


First of course there is the HTTPService tag. Basically similar (as far as i can tell) to the <form> HTML tag. You specify the URL which is the "action" of a <form> and then of course the method, POST, GET and others i cant remember! all you need for a very basic form is the URL and the action parts and of course the ID which is used later to submit it. The interesting part is the "result" property. This is a property that defines what to do if/when the form receives an answer from the script, in my example i used the php: or die("failed") to provide feedback to the flex form. It automatically receives the text "failed" if the PHP encounters an error (for example your mail server dies and your user thinks a message has been sent but it hasnt. The error handler will notify the user of an error). In my example i created a function that i will explain in a sec, that takes the value of 'event' which will contain the text from my php file. So if my PHP die statement was: or die("no luck"); then the resulthandler(event) would pass on the value "no luck" to my function. You also need to specify the format of the result. In this case it is text. You can also use XML feedback for moe complex things like database functions. Anyway....

The next part is this:

CODE
<mx:request xmlns="">
            <name>{fname.text}</name>
            <email>{email.text}</email>
            <message>{message.text}</message>
        </mx:request>
    </mx:HTTPService>


HTTPService is more like a function really as explained in the adobe reference library to flex it is "When you call the HTTPService object's send() method, it makes an HTTP request to the specified URL, and an HTTP response is returned. Optionally, you can pass parameters to the specified URL."

So you your partially right on what HTTPService is supposed to do. Also with this they only use the POST and GET functions for now and I am not aware of any others that can be used.

From my understanding of what xmlns is, it specifies the declaration of the XML version. However, while fiddling around with it I believe xmlns has others uses as well. Any way you don't want to change 2006 as that is the current version being used by flex, 2003 is flex 2. As for the request tag itself from the examples I have seen it <mx:request xmlns=""> remains blank. However, check out this link

http://livedocs.adobe.com/flex/2/langref/m...TTPService.html it could give you a broader sense of what is going on and also check out this example of how the request tag is being used and from the looks of it it seems you make the actual request within that tag.


QUOTE

This basically sets the data to be transmitted to the URL specified in the first code block. In my example i have the users name, email address and their message. Basically my PHP code receives a variable named "name" containing the data from the fname text input box (this is set by the code: {fname.text} ) Now as you notice this code comes WITHIN the mx:HTTPService tag which is now ended after the mx:request tag. AS far as i know the xmlns property doesnt need to be filled in. I may be wrong but it works so far!

Now we need to define our functions that submit the form and process the feedback.

firstly you need (it seems) to import the controls form the library inside the mx:Script tag:

CODE
<mx:Script>
        <![CDATA[

            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.controls.Alert;


You can see the Result and Fault Events have been included here as has the Alert controls because we will use an Alert to advise the user. Now we need to create our function to submit the form to the PHP program. I have called my function "sendmyemail" you can call it what you want. Youll notice i have also used the ID i set for my HTTPService which is "sendmycontact" (If you are confused see the first code block)

CODE
function sendmyemail():void
        {
        sendmycontact.send();
                
        sendmycontact.resultFormat = "string";
        sendmycontact.addEventListener(ResultEvent.RESULT, resulthandler);
        sendmycontact.addEventListener(FaultEvent.FAULT, fault_handler);
    }
With all the scripts that I have seen almost everyone uses the importing function and I haven't look into much on where the imports are coming from. With the id that is used to help identify what is interacting with who and if notice in my tutorials it help identify what was ot be validated and what not.



QUOTE
Im not sure why we have the ":void" after the function declaration... But its a fact of life! It seems to replace "functionname(void)" in other languages (i have very little experience of actionscript and OO JS). EDIT: I have just discovered the meaning of the :void. It is the declaration of the type (eg string, int) that the program can expect. So as the program is going to receive a NULL value (void) the variable "type" is void, and the way to write that is :void an integer return would be :int and so on smile.gif. The part that submits the form is the "sendmycontact.send();" statement. So now the form is sent. If you dont want to provide feedback on errors or success then that is the only line you need. However i will continue! Again we declare the format of the result expected from PHP You now see we are adding EventListeners to our HTTPservice, one to listen for a positive result, and one to listen for an error known by flex as a FAULT. First you tell flex you wish to add a listener with sendmycontact.addEventListener now you tell it to listen for a result/fault event with "(ResultEvent.RESULT," (substitute result for fault of course for a fault report) and then we name that listener as "resulthandler" or "fault_handler" respectively. Any names can be used here. So now the form has been submitted and flex is eagerly listening to the PHP for any sort of output. When it receives that output it will be put into resulthandler(event) as the <mx:HTTPService> Tag defined. So now we need to create this function using the following code:
CODE
function resulthandler(event):void{
            if(event.result == "failed")
            {
            fault_handler();
            }
             else
             {
                Alert.show("Thanks! Your comments have been emailed and we will reply shortly if required.", "Thanks!");
            }
            }




As with the void function it is more or less telling telling the script what to do once the request is made, again refer to how I the void is used for reset function I set up.

QUOTE
So we take the value of "event" given to use by the HTTPService tag which is of course the output from PHP. (again im not sure why the :void is there but it seems to work! Feel free to correct my codes, ive only been learning flex for about 18 hours!) Now For some reason we must use the "event.result" variable/property of the event which contains the actual PHP output. In my PHP i wrote or die("failed") so in the event of some error my PHP output is simply the word failed so my IF statement logically checks to see i the output was "failed" If it was then there was of course an error and i need to notify my user and i do so using the fault_handler() function explained in a sec. The else statement of course is there in the event that the output is NOT the word failed (hence the PHP succeeded and the email was sent) then we can tell the user the email was sent using that alert box there. The first string is the message displayed and the second, shorter string, is the text of the alert box's title bar. So the user is greeted with a message saying they have done their part and can wait for the reply or whatever.

CODE
function fault_handler():void{
                Alert.show("The operation failed. Your comments were not received due to a technical failure. Please try again later after we have fixed this problem", "Failed");
        }


This is the opposite function that simply gives an alert telling the user it failed and to try again later.

And that my friends is that! Of course to trigger this lot off you need to use: click"sendmyemail()" in your submit button.

As i said ive only been learning flex since last night so this isny fool proof and its not very neat. But it gives you a nice starting point. What i would really like to find out is how to prevent my form being submitted if my validation (see SM's tut) flags up an error. Im working on that now!! But if you know an easy solution to that then reply and let me know biggrin.gif


I think I know what your asking for but it make take some more searching, but there is a way to prevent the form from being sent unless you filled out the required info in the form. However, I think you like this function required="true", with this regardless if you do the validation a person is still required to fill it out before submitting anything so look at this link http://flexlib.googlecode.com/svn/trunk/do...vancedForm.html and you could get an idea on what to do with that aspect of the form.

 

 

 


Comment/Reply (w/o sign-up)

shadowx
Thanks SM, after a bit of tinkering i made a simply validation function, its not the most elegant solution but given my lack of flex knowledge i just used the same logic i would use with PHP or JS and came up with this:

CODE
function sendmyemail():void
        {

                    <!-- Added validation code: -->

            var instringAT:int = email.text.indexOf("@");
            var instringDOT:int = email.text.indexOf(".");            
            if(instringAT < 4 || instringDOT < 9){
                Alert.show("Please enter a valid email address to continue", "Invalid Email");
            }

            

            if(fname.text.length < 3 || email.text.length < 12 || message.text.length < 25) {
                Alert.show("Please fill in the form completely paying attention to any field with a red border. All fields are required.", "Error");
            }
            else
            {

            <!-- Original "senmyemail" code:  -->    
    
        sendmycontact.send();
        btnsend.enabled = false;
        btnsend.label = "Sent"
        sendmycontact.resultFormat = "string";
        sendmycontact.addEventListener(ResultEvent.RESULT, resulthandler);
        sendmycontact.addEventListener(FaultEvent.FAULT, fault_handler);
    }
    }


Basically i just check the length of the value of the text boxes and for the email i do a search for the @ and . (DOT) characters. If it fails any of those checks they get an error. If its good it passes on to the code that sends the request. I also added a line to disable the send button and change its text to "sent" as soon as the request is sent.

Ive just uploaded it to http://shadows.trap17.com/flex/ Ive changed the PHP so it does nothing and you will always get a nice thanks message, but if you enter your name as "failure" you will get a failed message (the irony!) Just to illustrate it all! And remember kids, the form was built basically from SM's tutorial just with less fields!

Comment/Reply (w/o sign-up)

iGuest-Bruce Whealton
Form not sending email
Submitting A Form In Flex (follow Up Of Sm\'s Tut)

Nice tutorial but I cannot figure out why the form content is not being emailed. My php form mailer does what most form mailers must do. I takes the data that is sent in the _POST[] variables from the form and emails this information to the emails specified. Things are not getting to my form correctly for some reason.

Everything seems to work with the code in terms of what an be observed and what we expect to see. It says that the form results were successfully emailed to us. However, the email never came. Any idea as to how I could figure out what went wrong? When I debug this, what should I examine and check?

Thanks,
Bruce

-question by Bruce Whealton

Comment/Reply (w/o sign-up)



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : submitting, form, flex, follow, sms, tut,

  1. How To Design A Contact Form In Flex Part Duex Part 2
    (0)
  2. How To Design A Contact Form In Flex Part Duex Part 1
    (1)
    How to Design a Contact Form in Flex Part Duex Part 1 Well if you had read my first three
    tutorials on how to design a contact form, you learn some basics on MXML and of course design a
    contact form. Yeah I promise a part 4 to that series, that is why I renamed this one to Part Duex,
    since the form is completely different, and using a different way to populate my combo boxes with
    data. Although, I might have found something to get the php going for this, but I save that for
    another time. Now because I am using the flex editor to design my contact form, I will be re....
  3. Design A Contact Form In Flex Part 3
    (4)
    Design A Contact Form In Flex Part 3 Hopefully you have able to get a grasp on my first tutorials
    on how to design a flex form and then be able to stylize it with CSS. So now on to set up your form
    to validate and of course being able to reset your form as well., and before we get to the actual
    coding I break down the tags that will be used in this tutorial and what their roles are. Of course,
    since my newbieness really starts here I try my best to explain these tags. The first tag I will
    cover for setting up the validation is the tag, and since I don't underst....
  4. Design A Contact Form In Flex Part 2
    (0)
    Design A Contact Form In Flex Part 2 I hope that you learn a little bit of the Flex format with my
    first tutorial because that was the easy stuff until you get to the actual programming such as
    ActionScript and any other languages. Of course, I think this is by far the easiest part of
    designing forms or applications and that is using CSS. I will like to point out that CSS in Flex is
    a enigma and I will tell you why, because CSS in flex acts like regular CSS in html however it is
    very limited in what you can use and yet CSS in Flex is very complex because of how you ca....
  5. Design A Contact Form In Flex Part 1
    (0)
    Design a Flex Form Part 1 Well this is my first tutorial on Adobe Flex 3 which is a great program
    if you’re interested in designing applications for the web 2.0 era. Adobe flex is the way to
    go as it combines several different programming languages in order to make the most out of this
    program. This includes HTML, CSS, XML, PHP/MySQL, XML, ActionScript, Ruby on Rails and ASP and this
    is all possible by the use of MXML or Magic eXtensible Markup Language because it is a user
    interface markup language. My three part tutorials for this form include designing the f....

    1. Looking for submitting, form, flex, follow, sms, tut,

Searching Video's for submitting, form, flex, follow, sms, tut,
See Also,
advertisement


Submitting A Form In Flex (follow Up Of Sm's Tut)

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com