Brian McGarvie | Find out more information on Brian M McGarvie and his IT consultancy, and personal adventures and experiences…

Jun/09

19

PHP Form Action Self submit

A question I am always asked is about ’self-submitting’ forms.

I’ll start off with the code!

myform.php

<form action="&lt;?php echo $_SERVER['SCRIPT_NAME']; ?&gt;" 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="&lt;?php echo $_SERVER['SCRIPT_NAME']; ?&gt;" 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

}

?>

Bookmark and Share

RSS Feed

No comments yet.

Leave a comment!

«

»

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

Find it!

Tags