Form Validation with PHP and Javascript: No Refreshes
This is a repost of one I did a while ago and deleted, but I like it so I’m going to post it again!
I was fooling around with CSS and Javascript and eventually started to mix the two into PHP. Using two frames, one spanned 100% of the page (thus, it’s like there is no frame) and the other one just there to load new bits of Javascript. The form posts data to the other frame, which is a PHP script, and PHP works out Javascript depending on the information it received. Within the HTML form (the main frame), we have hidden div’s that contain error messages, when PHP find something that doesn’t validate, we output Javascript to un-hide those div’s and thus display the error messages. Look at the bottom of this post for a working example.
We’ll use a user sign up form throughout this post to demonstrate. It’s really quite nifty
We’ll start off with a standard frameset. Like I already said, the main frame can take up the entire screen, so the user never needs to know it was there.
[code lang="xml"]
[/code]
Note that I made the main frame 90% instead of 100%. This way you can see the output that PHP makes by right-clicking the frame and “view source”.
Next there’s the HTML form, which in the frameset I’ve called ‘html.html’ (how original!):
[code lang="xml"]
[/code]
There’s some useless CSS and JS in there that makes the form elements highlight when you hover over them, you can ignore those bits (like I said, I was fooling around ;-)). The most important parts are the error divs, which are of class ‘error’. In this script, their ID must be “error_x”, where X is the name of the form field. For example:
[code lang="xml"]
[/code]
The field name is ‘username’, thus the ID of the error div has to be ‘error_username’. If you had a field named ‘i_hate_fish’, the error div would be ‘error_i_hate_fish’. Of course you could always alter the PHP script to give whatever names you wanted, but I find it easiest this way. Also note the style display property is set to ‘none’. We want it to remain hidden until the user has an error with a particular form field.
The next thing to notice is the form’s action, target and id:
[code lang="xml"]
October 6th, 2004 at 2:04 pm
i had a question about this page.
http://www.chroder.com/index.php?p=6
i want to set the default state of a table to start out not showing, without using cookies (which i dont understand) or anything too special. how would i go about doing that?
thanks a lot btw
October 6th, 2004 at 6:19 pm
To start it out not showing, just add style=”display:none” to each thing you want to be hidden (the tbody’s).