It's a bit confusing, because during the second pass the same JS code is performed, that is, document.write function performs the same writing of html code, before the php part is executed.
My tutorial contains no explanation of what actually happens with variables during the execution this type of php script.
I also don't know much about $_POST array.
So, I can see here the same code is executed twice, but with different outcomes.
Could You please explain, why after SUBMIT action (calling the same script again), an ordinary html code writing doesn't take place (every time). I mean why document.write function is not called during the 2nd pass?
I would like to know about 'technique' of initialization after Submit action.
Maybe You can refer me to some link about this matter.
When you submit a form to a PHP page, a special global array calle $_POST is populated with all the values sent by the form. The array key for each value is the name of the form element. So in your example, the value of the input field which you have named "var" (name=var) is stored in the array element $_POST['var']. Depending on the settings under which PHP is running on your web host -- specifically if "register_globals" has been turned on -- then the variable $var is also created and contains that same value. For best script portability as well as avoidance of namespace problems, it would really be best for you to use $_POST['var'] in your script instead of $var, or else explicitly set $var = $_POST['var'] before using it.
Anyway, until you actually submit the form, nothing is populated in the $_POST array or its related register_global variable $var. Therefore it has a null or empty value when referenced.
Therefore, a better way to write that last "echo" line of the script would be:
PHP Code:
if(!empty($_POST['var'])) # if form has submitted the field and it's not empty
{
echo "<p>Value: {$_POST['var']}</p>\n"; # use {} for array value within "..."
}
else
{
echo "<p>Please enter a value above then click the Get button.</p>\n";
}
Also, unless there is other stuff going on in the script we're not be shown, I see no reason for the use of JavaScript (especially since the page will therefore not work if Javascript is not enabled on the user's browser).
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks