Web Forms

1 May 2011

One of the places where HTML, JavaScript and PHP are in perfect harmony is web forms.

Forms are defined by the form tag and can contain most of the other HTML tags. Out of those, input elements (such as text boxes) pass data to the server. The name attribute of an input element can be thought of as a variable which the web server reads. For example:

<form action="comments.php" method="post" name="myform">
	<input type="text" name="email"/>
	<input type="submit"/>

will generate a textbox with a button. After the user clicks the button, the server can read the text from within comments.php via $_POST[email].

There are actually two methods which post the data:

  • GET: The variables are appended by the browser to the address such as "script.php?var1=value1&var2=value2
  • POST: The variables are passed via the HTTP protocol rather than as part of the URL.
Both of those are readable in PHP by the $_GET and $_POST global hashes. If the page expects either, $_REQUEST contains their union.

What's sleek about forms is that it is trivial to add client-side error checking in JavaScript. This will not replace proper server-side verification as it is easy to bypass, but might help reduce unneeded server load and annoyance of the user while waiting for the page to refresh. We need to define a boolean-returning function and add onsubmit="return checkEmail()" to the from declaration. If checkEmail() returns true, the form is submitted, otherwise the button click is silently ignored. I used:

function checkEmail()
	if(!document.myform.email.value.match("^.+@.+\..{2,4}$")) {
		alert("Please enter a valid email.");
		return false;

	return true;

where we use the convenient match() method of the String object to test the string against a Perl regular expression.

This was my web forms in a nutshell. You can see & test the complete implementation in the blog's comments by using them :)

Comments for Web Forms

Sudnya on May 4, 2011, 1:43:47 am EDT

When I start posting a, the comment box contains this pre-existing text "Comment up to 2k characters..." Might be an interesting enhancement to make it disappear as soon as the commenter clicks on the comment box :) Anyway, I was here to say post something about encoding email contact on the website with SPAM protection :D

Rouslan on May 4, 2011, 3:16:32 am EDT

Done. Thanks for suggesting!

Deni on May 6, 2011, 5:00:39 pm EDT

Well, these sound like pretty good Web forms and a Blog making recipes but I wouldn't try them this weekend :). Instead I can give you one promising recipe for cookies but the ones that you can taste ;)

Rouslan on May 6, 2011, 5:09:23 pm EDT

Mmm, my favorite cake with strawberry icecream? :)

Deni on May 6, 2011, 5:15:56 pm EDT

We'll add it to the weekend flour - made adventures! ;)

Post a new comment

Name: Comment:
4 + 2:
7 characters word: