Broad Network


Same Page Form Feedback with PHP

Professional Approach

Forward: In this article I show you how to produce same page form feedback with PHP.

By: Chrysanthus Date Published: 14 Nov 2012

Introduction

You might have come across web page forms were if the user makes a mistake in filling the form the error message would be displayed (usually in red) just above the particular form control (field). I show you how to do that with PHP in this article.

You need basic knowledge in HTML (or XHTML) and PHP in order to understand this article. If you do not have basic knowledge in HTML then read the series I wrote whose first part is titled, “Getting Started with XHTML”. To arrive at the series, type the title and my name Chrys in the Search Box of this page and click Search. If you do not have basic knowledge in PHP then read the series I wrote whose first part is titled, “Getting started with PHP”. To arrive at the series, type the title and my name Chrys in the Search Box of this page and click Search.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Example HTML Form
We shall use the following HTML form for illustration:

<html>
<head>
</head>
<body>
    <form method="post" action="myPHP.php">
                                                                 <br />
        Name: <input type="text" name="Name"><br />
                                                                 <br />
        Email: <input type="text" name="Email"><br />
                                                                    <br />
        Message: <textarea cols="50" rows="3" name="Message"></textarea><br /><br />
        <button type="submit">Send</button>
    </form>
</body>
</html>

In the form the method is POST and the action attribute has the name of the PHP file, myPHP.php. This PHP file and the HTML file for the form are in the same directory at the server.

Feedback Strategy
Now the PHP file (script) has a copy of the HTML Form web page file code and it slots small PHP code segments where error messages are expected in the copy. For the HTML code above, a small PHP code segment will be slotted just above the tag for a control in the copy. Each control tag in the copy will have a particular PHP code segment above it, which is responsible for its error message.

At the beginning the user will call the HTML form at the browser. The fields will be empty. He then fills the form and clicks the Send Button. The PHP program (myPHP.php) is called. The PHP program will validate the controls and if there are errors a small PHP code segment above a control tag (copy) will send an error message back to the browser.  If there is no error, then the only message sent back would be that the form information has been successfully received.

Now, if after feedback has been sent with error message and the user makes an error again, the PHP script will still be run because the copy of the web form now at the browser still calls the same PHP script from its action attribute. So, after the first error has been committed by the user, the PHP script will keep calling itself, as long as the user keeps making errors and clicking the Send button.

A Simple PHP Program
There are four main code segments in the simple PHP program (script) I will give you. It works with the above HTML file. The first of these code segments will get the values of the controls sent from the web form. The second of these segments will validate the controls and if there is any error, it will set certain flag variables. If there is any error the third of these segments will send a complete copy of the web form with slotted error messages back to a new page at the browser. If there is no error, the fourth of these segments will send a confirmation (saying form information successfully received) to a new page at the browser; in this case the copy of the web form will not be sent back.

The First Main Code Segment
This is the first main code segment of the PHP script:

//obtain values from web form
$NameVal = $_POST['Name'];
$EmailVal = $_POST['Email'];
$MsgVal = $_POST['Message'];

There is a global predefined array called $_POST  in PHP. If you send the HTML form information by the post method then this array will have the values of the controls sent. To get the value of each control, you need the name of the control. You assign the return value to a variable with any name you want.

The Second Main Code Segment
This is the second main code segment:

//error flags
$errorOccurred;
$nameError;
$emailError;
$msgError;

//simple validation
if ($NameVal == "")
    {
        $errorOccurred = "true";
        $nameError = "true";
    }
if ($EmailVal == "")
    {
        $errorOccurred = "true";
        $emailError = "true";
    }
if ($MsgVal == "")
    {
        $errorOccurred = "true";
        $msgError = "true";
    }

The first four lines above are error flags (variables). If there is any error at all, typed (caused) by the user, then the $errorOccurred variable will have the value, “true”. If there is an error with the user name, then $nameError will have the value “true”. If there is an error with the email, then $emailError will have the value “true”. If there is an error with the message field then $msgError will have the value, “true”.

After the above four lines, you have four if-constructs. These four constructs do some simple validations of the sent field values. They simply check if a field value was empty. You can make the validation more complicated than this if you want to, but I will not go into that in this article. If any field value is empty, then the generalized error variable, $errorOccurred is given the value, “true”; also the corresponding error variable is given the value, “true”. The values of these flag variables will be used to determine if feedback error messages are to be sent back to the browser.

The Third Main Code Segment
This is the third main code segment:

//display copy and error messages if error occurred
if ($errorOccurred == "true")
    {
        echo "<html>\n";
        echo "<head>\n";
        echo "</head>\n";
        echo "<body>\n";
        echo "    <form method=\"post\" action=\"myPHP.php\">\n";
        if ($nameError == "true")
            {
                 echo "<span style=\"color:red\">The Name field cannot be empty!</span>";
            }
        echo "<br />\n";
        echo "Name: <input type=\"text\" name=\"Name\" value=\"" . $NameVal . "\"><br />\n";
        if ($emailError == "true")
            {
                 echo "<span style=\"color:red\">The Email field cannot be empty!</span>";
            }
        echo "<br />\n";
        echo "Email: <input type=\"text\" name=\"Email\" value=\"" . $EmailVal . "\"><br />\n";
        if ($msgError == "true")
            {
                 echo "<span style=\"color:red\">The Message field cannot be empty!</span>";
            }
        echo "<br />\n";
        echo "Message: <textarea cols=\"50\" rows=\"3\" name=\"Message\">" . $MsgVal . "</textarea><br /><br />\n";
        echo "<button type=\"submit\">Send</button>\n";
        echo "</form>\n";
        echo "</body>\n";
        echo "</html>\n";
    }

All the code here is in one big if-construct. The condition of the big if-construct first checks if the value of the generalized error variable (errorOccurred) is “true”. If it is true then a copy of the web page has to be sent back to the browser, with error massages slotted at relevant positions.

The PHP echo function is used to send the lines of the copy of the web page.

Now, note the small PHP code segments just above the tags of each control in the copy. Each of them is an if-construct, which checks if the corresponding flag variable is “true”. If it is true, then the block of the if-construct sends the error message.

Note that while sending a copy of the control tags, the value of the control, which is what the user typed, is also sent; with this the user may not have to retype the field value.

So the third main code segment (block of large if-construct) operates only if there was at least one error. If there was no error, then the third main code segment will not operate; it is the fourth main code segment that will operate.

The Fourth Main Code Segment
This is the fourth main code segment:

//if no error occurred, send feedback that web info has been received
if ($errorOccurred != "true")
    {
        echo "<html>\n";
        echo "<head>\n";
        echo "</head>\n";
        echo "<body>\n";
        echo "<h1 style=\"color:darkblue\">Thank you.</h1>\n";
        echo "<h2 style=\"color:darkblue\">The Information has been received.</h2>\n";
        echo "</body>\n";
        echo "</html>\n";
    }

This segment is another large if-construct. It checks if there was any (at least one) error using the generalized error variable, errorOccurred. If there was no error, then it sends a confirmation message to a new page at the browser. With this script you do not need any special statement to send the tags to a new browser page. If the script was called from the browser, then each echo instruction will send its argument to the same web page at the browser.

Remarks
In practice, for the web page, you may want a heading at the top of the form to indicate that an error has occurred, in one of the controls, and then the user can scroll down to see the particular control and its error. You can achieve (code) that using the generalized error variable, errorOccurred. In the web page copy in the script an H3 element with the generalized error message can be sent just below the start tag of the form.

After the PHP script has successfully received the values of the form controls, you can do whatever you want to do with the values. You can send them to a database; you can send them to a printer or you can send them to an email box. Consult my article series on how to send email with PHP, titled, Sending Email with PHP.

Downloads
I have put the HTML file and the PHP script in one zip file. You can download the zip file from,

http://www.broad-network.com/ChrysanthusForcha/Same-Page-Form-Feedback-with-PHP.zip

Download the zip file, unzip it and put the two files in one directory in your web server. Use a browser to open the HTML file and test.

Conclusion
To have same page feedback for a web form, the PHP script called should have a copy of the web form page. If there is an error message, the copy is sent back with the error message slotted at a relevant position of the copy. The copy is in echo statements and not in isolation. The web (HTML) form is called once; after that if the user keeps making errors, it is the PHP script that will be called (calling itself) over and over again.

Chrys

Related Links

Same Page Form Feedback with PHP
Same Page Form Feedback with JavaScript
Same Page Form Feedback with Active Perl
Major in Website Design
Web Development Course

Comments

Become the Writer's Fan
Send the Writer a Message