# Making web forms



## Highlander II (Dec 31, 2008)

Okay, so I'm going to be working on a web-based form and while I've put them together before and gotten the fields to layout nicely and such, I can't seem to figure out how to get it to _email_ the form where I want it to go. 

Or, rather, it will send a lovely BLANK email, but the form and all of its data are missing.

Does anyone have any good suggestions for places to get info on setting up some form variables and getting the form to send the data?

I'm also wanting to have part of the form choose a random question from a bank of questions, so I'll need to know how to make it do that - ie: choose a new question on refresh - which I haven't done before.


----------



## Highlander II (Jan 3, 2009)

Huzzah!  I have created the form and I *sort of* have it set to email the data as I want.  (It opens an email client rather than just 'sending' the data - but it's better than the 'not sending' that the last one I tried was doing.)

Now - the hard part.  At least, for me, since I haven't done this and I'm having a rough go of describing it well enough for google to find what I'm looking for. *g*



I want to be able to define a set of questions, then have one of those randomly called when the page is loaded or refreshed into a section of the form.

I'm sure it can be done, probably with javascript, but I'm not sure exactly how to set up the code.


----------



## Highlander II (Jan 13, 2009)

Okay, I've found the javascript code to do what I wanted on my form.  One small glitch - every now-and-then I'll get a value of 'undefined' on the refresh.  

Here's the code - can anyone tell me why I get this value?

Thanx for any help! =)

(if you need to see the entire form, lemme know and I can link that too)


```
<script><!--
function get_random(maxNum)
{
if (Math.random && Math.round)
{
var ranNum= Math.round(Math.random()*(maxNum-1));
ranNum+=1;
return ranNum;
}
else
{
today= new Date();
hours= today.getHours();
mins= today.getMinutes();
secn= today.getSeconds();
if (hours==19)
hours=18;
var ranNum= (((hours+1)*(mins+1)*secn)%maxNum)+1;
return ranNum;
}
}

function getaQuote()
{
var maxQuotes=10;
var whichQuote=get_random(maxQuotes);
whichQuote--;

var quote=new Array(maxQuotes)
quote[0]="What is the name of the wiki?";
quote[1]="Name two of the <i>Fallout</i> games.";
quote[3]="What are two location names from <i>Fallout (1)</i>?";
quote[4]="What is a G.E.C.K.?";
quote[5]="What does SPECIAL stand for?";
quote[6]="What are two creatures that one can face in the <i>Fallout</i> world?";
quote[7]="Name two items that one might collect in <i>Fallout</i>.";
quote[8]="Are the Skulz a real group in <i>Fallout</i>?";
quote[9]="In which game is the initial quest to locate a waterchip?";

document.write(quote[whichQuote]);

}

getaQuote();

//--> </script>
```


----------



## Lenny (Jan 15, 2009)

If JavaScript follows the Java syntax, then after a quick glance through I think you're missing a couple of braces. It's hard to see without everything indented (a fault of the forum), so I'll go through it again and indent things myself.

Be right back!

---

EDIT: Try this:


```
<script><!--
 
function get_random(maxNum){
 if (Math.random && Math.round){
  var ranNum = Math.round(Math.random() * (maxNum-1));
  ranNum += 1;
  return ranNum;
 }else{
  today = new Date();
  hours = today.getHours();
  mins = today.getMinutes();
  secn = today.getSeconds();
  if (hours == 19)[COLOR=red]{[/COLOR]
   hours = 18;
   var ranNum = (((hours + 1) * (mins + 1) * secn) % maxNum) + 1;
   return ranNum;
  [COLOR=red]}[/COLOR]
 }
}
 
function getaQuote(){
 var maxQuotes = 10;
 var whichQuote = get_random(maxQuotes);
 whichQuote--;
 var quote = new Array(maxQuotes)
  quote[0] = "What is the name of the wiki?";
  quote[1] = "Name two of the <i>Fallout</i> games.";
  quote[3] = "What are two location names from <i>Fallout (1)</i>?";
  quote[4] = "What is a G.E.C.K.?";
  quote[5] = "What does SPECIAL stand for?";
  quote[6] = "What are two creatures that one can face in the <i>Fallout</i> world?";
  quote[7] = "Name two items that one might collect in <i>Fallout</i>.";
  quote[8] = "Are the Skulz a real group in <i>Fallout</i>?";
  quote[9] = "In which game is the initial quest to locate a waterchip?";
 
 document.write(quote[whichQuote]);
}
 
getaQuote();
 
//--> </script>
```
 
I'm not completely sure if the quote[x] bit is right, but I'll leave that for now.

_EDIT3: Just looked it up - you're correct with it. I thought it might have needed a ; when you defined the new array, or to have opening and closing braces around it, but apparently not. You learn something new every day!_

What I've added is in red, and everything is nicely idented (well, just about - it looks nice in Dreamweaver ). It doesn't _need_ to be, it's just good practice, and it makes it a lot easier for others to read. Some of the changes I've made (added opening braces to the end of lines rather than them being on their own line, and spacing before and after operators, for example) are personal preference.

I assume there's a lot more to the script/another script which the page links to/is in script tags?

EDIT2: Oh, and I bet it doesn't work - not because I've killed it, but because changing some of the syntax means that the rest needs to be syntactically correct to work properly... assuming that JS and Java share the basic syntax.


----------



## Highlander II (Jan 16, 2009)

Would you like to see the entire form?

Enter the Wastelands - Character Application


----------



## Lenny (Jan 16, 2009)

Thankee kindly.

I copied the source into Dreamweaver and replaced the scripts with my editted version, and there were still some instances of "undefined". I'm in the middle of packing my bags at the moment, but when I've got time (it might be tonight if I'm lucky, or over the weekend, but I wouldn't hold my breath - I return to Uni tomorrow morning, so I haven't a clue what spare time I'll have) I'll go through it and debug it. My guess is that the number returned as whichQuote is greater than 9, which is not a defined quote. I'm not totally sure, though.

If you manage to fix it in the meantime, I'd like to know what you do.


----------



## Lenny (Jan 16, 2009)

Packing's doing my nut in, so I took some time to look at this. You're going to kick yourself, you really are. 

First, I'll tell you what I was doing before I noticed the error:

Everytime a variable was declared, or had a value assigned to it, I added a new line after it - *alert(*_variablename_*);*. When the code hits that line, it pops up a message box. Replace _variablename _with a variable name (let's take ranNum as an example from your code) and the message box will contain the value of that variable. If you're going to have a lot, then you simply add something in quote marks, and a plus - *alert(*"lookee! Text" +* variablename);*.

Anyway, I added an alert everytime a variable was changed, and eventually narrowed the undefined down to when the random number generated was *2*. By the way, do you need to add one to ranNum? It gets passed down to whichQuote, and has the one taken off again... which, to me, seems a bit pointless. Also a note, in cases where you're adding one you can use *++* (in much the same way as you use *--* to take one off) rather than *variablename += 1*. In the code below I've highlighted the lines I don't think you need in red, with my additions and changes in green.

So yeah, narrowed it down to when the result was 2. At that point I went into the getaQuote function and added alerts there (I'd only put them in get_random to begin with). After a few minutes of tinkering, the problem reached out and poked me inna eye - generally, when counting, _2_ comes after 1, not 3.  And that's it. Which explains why when the ranNum is 2 the question asked is undefined - there is no *quote[2]*.

I've re-numbered the quotes, knocked one off maxQuotes, and coloured my changes/thoughts:


```
<script><!--
 
function [COLOR=blue]getRandom[/COLOR](maxNum){
 if (Math.random && Math.round){
  var ranNum = Math.round(Math.random() * (maxNum-1));
  [COLOR=red]ranNum += 1;[/COLOR]
  return ranNum;
 }else{
  today = new Date();
  hours = today.getHours();
  mins = today.getMinutes();
  secn = today.getSeconds();
  if (hours == 19)[COLOR=seagreen]{[/COLOR]
   hours = 18;
   var ranNum = (((hours + 1) * (mins + 1) * secn) % maxNum) + 1;
   return ranNum;
  [COLOR=seagreen]}[/COLOR]
 }
}
 
function get[COLOR=blue]A[/COLOR]Quote(){
 var maxQuotes = [COLOR=seagreen]9[/COLOR];
 var whichQuote = [COLOR=blue]getRandom[/COLOR](maxQuotes);
 [COLOR=red]whichQuote--;[/COLOR]
 var quote = new Array(maxQuotes)
  quote[0] = "What is the name of the wiki?";
  quote[1] = "Name two of the <i>Fallout</i> games.";
  quote[[COLOR=seagreen]2[/COLOR]] = "What are two location names from <i>Fallout (1)</i>?";
  quote[[COLOR=seagreen]3[/COLOR]] = "What is a G.E.C.K.?";
  quote[[COLOR=seagreen]4[/COLOR]] = "What does SPECIAL stand for?";
  quote[[COLOR=seagreen]5[/COLOR]] = "What are two creatures that one can face in the <i>Fallout</i> world?";
  quote[[COLOR=seagreen]6[/COLOR]] = "Name two items that one might collect in <i>Fallout</i>.";
  quote[[COLOR=seagreen]7[/COLOR]] = "Are the Skulz a real group in <i>Fallout</i>?";
  quote[[COLOR=seagreen]8[/COLOR]] = "In which game is the initial quest to locate a waterchip?";
 
 document.write(quote[whichQuote]);
}
 
get[COLOR=blue]A[/COLOR]Quote();
 
//--> </script>
```
 
So:

Green - my changes
Red - code that I don't think is needed
Blue - it's technically bad practice to use underscores in Java, and every word in a function/method name should have a capital letter. It's picky, yeah, but I'd count *a* as a separate word, thus the capital.

The only things that are needed are those in green - the code will still work if the things in red and blue are left unchanged, but it's bad practice. I'm half-tempted to say something about "var", but I really must get back to my packing. If I'm feeling especially pedantic, I'll come back to them. 

As far as my brief testing went, the above works. Unless I've copied and pasted it wrong.


----------



## Highlander II (Jan 17, 2009)

Thanx, Lenny!  I'll plug it in and see what happens! *g*


----------



## Highlander II (Jan 28, 2009)

Okay - so, this 'updated' code - didn't work so good.  Now I don't get 'anything' where the random questions should appear.  At least before I was getting something.  Now it's all blank.

I even just tried adding a quote[2] to the list - and it comes out blank.  Not sure why that is though, b/c it just seems odd.

updated code:  http://h2smsk.com/wastelands/charapp.html
old code: http://h2smsk.com/wastelands/charapp1.html


----------



## Lenny (Feb 5, 2009)

Just noticed your post.

It's a simple problem, luckily.

The start of the Javascript is on the same line as <!--, which turns it into a comment:


```
<script><!-- function getRandom(maxNum){
```
 
For both of them, it needs to be on a new line:


```
<script><!--
function getRandom(maxNum){
```


----------



## Highlander II (Feb 5, 2009)

Well that's just silly.  

However - guess what I'm off to do?  Yep - correct the script... freaking code!

Thanx, Lenny!! =)

http://h2smsk.com/wastelands/charapp.html - works now!


----------



## Highlander II (Jul 10, 2009)

Okay - so, my form works and it will even send w/ an external mail client (ie: Thunderbird or Outlook Express), but what if I want it to just send w/o needing the client?  How do I do that?

Enter the Wastelands - Character Application <- the form again.


----------



## Lenny (Jul 10, 2009)

I'll get back to you on that in a day or so, but whilst I'm here, could I make a suggestion about the design?

It's simply a thought about using tables to make everything line up. Take a look at the IM handles bit, for example. Rather than using spaces to line things up approximately, it might be nice to use a four-column jobby:

IM Client | Textbox | IM Client | Textbox


----------



## Highlander II (Jul 11, 2009)

yeah - and here is where i express my distaste for tables b/c i hate trying to read 'across' on something that's written 'down' (the code, that is) - it makes my brain hurt... 

is there something less annoying than tables to manage the same thing?  

I do get what you're saying - tables just bug me. =)  (though I may end up looking into it at some point when I'm not sleep-deprived. *g*)


----------



## Highlander II (Jul 11, 2009)

okay - I still hate tables, but I did rearrange the elements ->
Enter the Wastelands - Character Application

however - I can't get my background image to work.... grrrrrr


----------



## Highlander II (Jul 27, 2009)

Now all I have left are getting the background image to work and figuring out how to make the form mail w/o requiring an external mail client... b/c that one I just can't figure out.


----------



## Lenny (Jul 27, 2009)

Sorry - this completely slipped my mind. : embarrassed:

Firstly, I don't know if you've noticed, but the questions on the new form don't show up. This is because of the problem I mentioned in post #10.

Your code for the background image is spot on, but the background image doesn't exist - have a look at the URL you're using.

I haven't the foggiest how to send an e-mail without a client (unless you can write a script that uses an e-mail address built into the actual host. Alternatively, you can save responses to a database), so instead I use this: Free Form to E-Mail. No PHP or CGI required. Feedback Forms..Contact Forms..Autoresponders..Easy to use remotely hosted script..Create or build Forms Online. It's free, and it works - you might need to do a bit of juggling to get it working fully, but once you've got it working, you'll be larfink.

EDIT: Here's a small code snippet from a form I made using the above site to send the results to my e-mail (the key part is in red):


```
<form [COLOR="Red"][B]method="post" action="http://free.allforms.mailjol.net/u/117432.php"[/B][/COLOR]>
```

And another:


```
<form [COLOR="Red"][B]method="POST" action="http://free.allforms.mailjol.net/u/ab168c9a.php">[/B][/COLOR]
```

The URL to the PHP script that deals with it is different for each form - it's given to you when you create a new form on the site.


----------



## Highlander II (Jul 28, 2009)

*sigh*

I have the form processor set-up and the link in my form, but the 'submit' button does NOTHING. (ditto the 'Reset' button)  

This is why I cannot be a coder for money - I'd go broke yelling at the code.


----------



## Lenny (Jul 28, 2009)

I've changed a bit of your code (from charapp1b.html), done my own test and submitted it (you'll be able to tell it's mine by all the "Lenny TEST" answers there are). Let me know if you receive the e-mail. If so, I'll give you the code. If not, I'll try again with something else.


----------



## Highlander II (Jul 28, 2009)

Yup - I did get it.  =)

btw - NvU keeps 'realigning' some of my code - namely the javascript for the questions - which is highly frustrating, b/c then things stop working.  Is there a way to make it stop doing that?

Also - since your test form went through - is there a way to have the form indicate which random 'question' the user had to answer?


----------



## Lenny (Jul 28, 2009)

I'm not sure about nVu - I can't say I've ever actually used it.

There is a way, yes:


```
<b>Q: </b>
[COLOR="red"][B]<input id="rulesquestion" name="rulesquestion" type="text" value="" readonly size="100">[/B][/COLOR]

<!-- random question from the Rules -->

<script><!-- 
function getRandom(maxNum){
if (Math.random && Math.round){
var ranNum = Math.round(Math.random() * (maxNum-1));
ranNum += 1;
return ranNum;
}else{
today = new Date();
hours = today.getHours();
mins = today.getMinutes();
secn = today.getSeconds();
if (hours == 19){
hours = 18;
var ranNum = (((hours + 1) * (mins + 1) * secn) % maxNum) + 1;
return ranNum;
}
}
}
function getAQuote(){
var maxQuotes = 9;
var whichQuote = getRandom(maxQuotes);
whichQuote--;
var quote = new Array(maxQuotes)
quote[0]="What is the character limit?";
quote[1]="What is rule #5 of the General Rules?";
quote[2]="Where does adult-oriented content belong?";
quote[3]="How often will threads be archived?";
quote[4]="What should be in the subject line of the first post of a thread?";
quote[5]="What is the name of the main town for Enter the Wastelands?";
quote[6]="What are the 3 required fields of the character profile?";
quote[7]="Are Random Encounters optional?";
quote[8]="Do all characters require a real-face PB?";
[B][COLOR="Red"]document.getElementById('rulesquestion').value = quote[whichQuote];[/COLOR][/B]
}
getAQuote();
//--> </script><br>
```

I've created a new text box, and told the script to write to the element in the  document with a specific ID (that of the text box you want the question in).

Do that for both the Wiki and Rules questions, and then go into your form on the allmail site to add them to it.

Oh, and to get it to work, add the table with the form bits into the actual form:


```
<form style="width: 950px;" name="application" action="http://free.allforms.mailjol.net/u/4b9c2809.php" method="POST" enctype="text/plain">

<table>
. . .
</table>

</form>
```


----------



## Highlander II (Jul 29, 2009)

Okay - now I'm not getting anything after the info in the 'player name' field... under pemail - all I get is 'pemail' - the name of the field.  *bangs head against wall*

and Nvu is nice for the 'coloring' - but it keeps moving the 'function' line back onto the same line as <-- and turning my functions into comments.... grrrrrrrrrrrrrrr

ETA:  did you get an 'auto-responder' e-mail when you submitted the form?


----------



## Lenny (Jul 29, 2009)

Indeed I did.

I haven't a clue what you could be doing wrong - I've just set up a sender for the same form, replaced your PHP link with the one given to me by allforms, and submitted everything fine.

Edit the form on AllForms - delete what you've got in there and re-enter it.

Oh, you also need to give the textarea's for Character Bio and Character Canon names - you won't get anything from those at the mo because they're not named.

EDIT: You'll also need to edit your reset button to reload the page - at the moment it does what a reset button should and clears the form... including the two question boxes. Replace it with:


```
<input value="Reset" type="reset" [COLOR="Red"][B]onClick="location.reload(true)"[/B][/COLOR]>
```


----------



## Highlander II (Jul 29, 2009)

I don't have a form on the all forms page - it says I don't have to build it there if I already have the html form built (unless I'm misunderstanding the directions - in which case - blah - too much trouble).  And, all told, I'd rather not have to redo everything building the form on the site since I've already coded it.

I built the form processor - but it still won't send all of the data - i only get the pname field and no auto-responder e-mail.


----------



## Lenny (Jul 30, 2009)

That's what I mean - go through the form processor on allforms (it's the one that makes you go through various pages asking for this, that and the other before it gives you PHP URL).

Your code for the form is fine (apart from the two missing field names) - I get a perfect result, which makes me think that the problem is your form processor.


----------



## Highlander II (Jul 31, 2009)

I did that - and I don't know what it could be missing... I input the information into the fields just like it asks.  I've done it twice - b/c I deleted the original and started over.

I've done it again giving it a list of 'required' fields... and now the thing tells me that some of the required fields aren't filled in, when they CLEARLY are... 

What am I missing?

ETA: took out the required fields b/c the error was stupid - even after i changed the charset to utf-8 - it still gave me the error... 

Now - I get a list of all of the field names, but i'm not getting any of the data in the fields...

i'll get you a screenshot of what I'm getting:  http://h2smsk.com/wastelands/etwformofdoom.jpg

it's getting stuck somewhere after the name field for some inexplicable reason


----------



## Lenny (Jul 31, 2009)

I'm stumped, I must admit. I can't see any obvious mistakes in the code that would make it return "pemail", and trying it again with my form processor, I get everything.

The only thing I can think of suggesting is that you completely delete the current form processor, and create a new one, leaving everything you can blank:

Choose the e-mail address
Leave Required Form Fields blank
Leave Order of Form Fields blank
Leave Subject, and the two page URLs blank
Choose the e-mail format (I always go for HTML - yes)
Choose if you want security code (I always choose yes)
Leave the entire next page blank
Name your form, and save it.

Replace the current PHP URL with the new one, and see if that works.


----------



## Highlander II (Aug 1, 2009)

Did exactly as you described and I still get only the name and 'pemail' under it.

I'm now about 14 seconds away from going to try to learn php and code it myself - which will only make me MORE angry b/c that'll take even longer.

It makes no sense - b/c if yours worked, mine should too and that's just - argh!

I quit.


----------



## Lenny (Aug 1, 2009)

The HTML I'm using is from charrapp1b.html that you've uploaded - is it the same as the one you're using?


----------



## Highlander II (Aug 2, 2009)

I have the same html, but w/ a different form processor URL in charapp1c too - and still - nothing.  I did try it w/ charapp1b as well.  

unless it's a web host thing - but I don't know what the webhost would be doing to block part of the data.


----------



## Highlander II (Apr 30, 2010)

Okay - I'm still trying to get this form to e-mail.  Rather than going through an external host, I'm considering using php to make it work.  

Below is example code that I've snagged from the web.  Do we have any php folks 'round who can take a peek and let me know if this is 'good', 'okay', or 'bad' code?  

I haven't changed anything - it's still the default code, but comparing this to the other code I found, this was the better choice - the first one used 'foreach' loops and that just seemed silly. XD


```
<?php
if(isset($_POST['email'])) {
	
	// EDIT THE 2 LINES BELOW AS REQUIRED
	$email_to = "[name]@[host].com";
	$email_subject = "Subject Line";
	
	
	function died($error) {
		// your error code can go here
		echo "We are very sorry, but there were error(s) found with 

the form your submitted. ";
		echo "These errors appear below.<br /><br />";
		echo $error."<br /><br />";
		echo "Please go back and fix these errors.<br /><br />";
		die();
	}
	
	// validation expected data exists
	if(!isset($_POST['first_name']) ||
		!isset($_POST['last_name']) ||
		!isset($_POST['email']) ||
		!isset($_POST['telephone']) ||
		!isset($_POST['comments'])) {
		died('We are sorry, but there appears to be a problem with the 

form your submitted.');		
	}
	
	$first_name = $_POST['first_name']; // required
	$last_name = $_POST['last_name']; // required
	$email_from = $_POST['email']; // required
	$telephone = $_POST['telephone']; // not required
	$comments = $_POST['comments']; // required
	
	$error_message = "";
	$email_exp = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$";
  if(!eregi($email_exp,$email_from)) {
  	$error_message .= 'The Email Address you entered does not appear to be 

valid.<br />';
  }
	$string_exp = "^[a-z .'-]+$";
  if(!eregi($string_exp,$first_name)) {
  	$error_message .= 'The First Name you entered does not appear to be 

valid.<br />';
  }
  if(!eregi($string_exp,$last_name)) {
  	$error_message .= 'The Last Name you entered does not appear to be 

valid.<br />';
  }
  if(strlen($comments) < 2) {
  	$error_message .= 'The Comments you entered do not appear to be 

valid.<br />';
  }
  $string_exp = "^[0-9 .-]+$";
  if(!eregi($string_exp,$telephone)) {
  	$error_message .= 'The Telphone Number you entered does not appear to 

be valid.<br />';
  }
  if(strlen($error_message) > 0) {
  	died($error_message);
  }
	$email_message = "Form details below.\n\n";
	
	function clean_string($string) {
	  $bad = array("content-type","bcc:","to:","cc:","href");
	  return str_replace($bad,"",$string);
	}
	
	$email_message .= "First Name: ".clean_string($first_name)."\n";
	$email_message .= "Last Name: ".clean_string($last_name)."\n";
	$email_message .= "Email: ".clean_string($email_from)."\n";
	$email_message .= "Telephone: ".clean_string($telephone)."\n";
	$email_message .= "Comments: ".clean_string($comments)."\n";
	
	
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  
?>

<!-- include your own success html here -->

Thank you for contacting us. We will be in touch with you very soon.

<?
}
?>
```


----------



## Lenny (Apr 30, 2010)

Middle of an assignment at the mo, but I just wanted to say that "foreach" loops aren't as daft as you may think.

A "foreach" loop is used on a collection of data - an Array, for example. Rather than having to define how many times a "for" loop iterates to go through everything in an Array, you simply use use a "foreach" loop. The Java syntax:

for([Element Type] : [Collection]{
. . .
}

The code within the loop will be applied to every element of the correct type within the collection.

---

I'm not a PHP coder, but I'll have a look at it over the next few days, if no-one else does.


----------



## Highlander II (Apr 30, 2010)

On the big ole internet, foreach loops may not be as bad as they are, in, say, an excel macro... b/c in excel, a 'foreach' loop will slow the process down - a lot - depending on what you want it to do and how many 'each's it has to look at. =)


Thanks, Lenny... no hurry - since I haven't touched the thing since August.


----------



## Lenny (Apr 30, 2010)

I can imagine it would! Excel is horrible for data and VBA does my nut in to no end.


----------

