A question I am always asked is about ’self-submitting’ forms.
I’ll start off with the code!
myform.php
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post"> I want to : <select name="selector"> <option value="null"></option> <option value="read">read a book</option> <option value="movies">watch a movie</option> <option value="music">listen to music</option> </select> <input name="submit" type="submit" value="Executer" /> </form>
In the above, this will simple subit the form and then you can do what you want with it. For example display some data, or if the form was to create a user account to insert that.
OK… you can also process the form depending on what’s been selected/entered and so on.
myform2.php
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post"> I want to : <select name="selector"> <option value="null"></option> <option value="read">read a book</option> <option value="movies">watch a movie</option> <option value="music">listen to music</option> </select> <input name="submit" type="submit" value="Executer" /> </form>
in this example if you select something, say ‘watch a movie’ and submit it, it will display: “Process ‘watch a movie’.”.
Some additional enhancements:
—————————–
The form action of course does not need to itself… you can put anything in action=”" if you prefere to process the form seperatley.
<form action=”…” method=”post”>
In my examples I have displayed the form only if it’s not submitted, this can also be done how you choose. Generally these would be:
ex1: form always present (below any resulting processing)…
<?php
if(!empty($_POST['submit'])) {
// Process form
}
// Show form
?>
ex2: form always present (above any resulting processing)…
<?php
// Show form
if(!empty($_POST['submit'])) {
// Process form
}
?>
ex2: show form only if not submitted
<?php
if(!empty($_POST['submit'])) {
// Process form
} else {
// Show form
}
?>
