Jump to content
xisto Community
Sign in to follow this  
shadowx

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

Recommended Posts

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.

 

 

<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:

 

<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:

 

<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)

 

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 :lol:. 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:

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.

 

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 ^_^

Edited by shadowx (see edit history)

Share this post


Link to post
Share on other sites

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.

<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:

 

<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

 

https://helpx.adobe.com/support.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.

 

 

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:

 

<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)

 

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.

 

 

 

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 :lol:. 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:

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.

 

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.

 

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 ^_^


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://forums.xisto.com/no_longer_exists/ and you could get an idea on what to do with that aspect of the form.
Edited by Saint_Michael (see edit history)

Share this post


Link to post
Share on other sites

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:

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://forums.xisto.com/no_longer_exists/ 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!
Edited by shadowx (see edit history)

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
Solution, thanks!Submitting A Form In Flex (follow Up Of Sm's Tut)

Thanks for this.  You answered my question of how to return results from PHP to Flex.  So may times answers are of the form, "See the documentation", which wasn't helpful the first time :)  Thanks!!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.