How do I submit a form's data automatically after successful PHP validation?

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
I made a form and used this for the submit button:

Code:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">

The validation part is fine, but how do I pass on the data automatically to the next page after validation has found that everything is ok?
 
Last edited:

beginner99

Diamond Member
Jun 2, 2009
5,315
1,760
136
explain more.

Also I'm not sure what this is for:

Code:
"<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"

Using just "" in action will "self-submit" too.
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Well you either need to store all your data in the users session, or store the data in your database and be able to use your users session to look up that data on the next request.
 

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
This is what I did in a nutshell:

Code:
<?php
// define variables and initialize with empty values

//error variables
$agentNameErr = "";

//non-error variables
$agentemail = "";
 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
if (empty($_POST["agentname"])) {
        $agentNameErr = "Missing";
    }
else {
        $agentname = $_POST["agentname"];
    }
}

// form

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >

<input name="agentname" type="text" id="agentname" autocomplete="on"  placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />

//only shows up if $agentNameErr is assigned the value of "Missing"

<span class="error"><?php echo $agentNameErr;?></span>

</form>

It checks if $agentname is erroneous (blank). If it's not blank, I don't know how to proceed. I want it to just automatically submit all the information without any additional user input after the user hits that first submit button.

In normal english:

Code:
//user presses the submit button

if ($agentname has error)
   stay on page and display errors
else 
   submit automatically to next page
 
Last edited:

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
PHP runs on the server, before the page is sent to the user. It can't run at the point that the user submits the page.

1. PHP + HTML defines page sent to user

2. User fills in page, hits submit, data is sent to server

3. Page code runs again on server, before anything is sent to user. You don't need to POST to the server because you are the server, you have the data already.

If the data passes validation, you can make MySQL calls now or whatever else you want to do. Then send a response like "Upload received" or a redirect to a new page.

If the data fails validation, display the normal page but with error note. Or if you're lazy just an error page and make them hit BACK.

=======

$errors = ""

If is POST data, validate

If all data present and OK, do_process_function()
Else do_show_form_function( $errors )
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
Why would you pass the data to another page? Any PHP code on that other page could be run on this page instead. The data is already there on the server, having the server send the data to itself makes no sense.

If you are trying to use a library of some kind, you would require_once() the library file then call it.

You don't normally want to send the data to another page. You want to process the data, then send the user's browser on to a new page.

You can navigate the user's browser to a new page by sending just a 302 redirect response, or by sending a response page with a META HTTP-EQUIV=REFRESH tag in the head.
 
Last edited:

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
In normal english:

Code:
Code:
//user presses the submit button

if ($agentname has error)
   stay on page and display errors
else 
   submit automatically to next page
__________________

It's important to get a firm grasp on where things are happening. There are two places code can run in this scenario: in the browser (javascript) and on the server (php).

The server runs php script to generate html which it sends to the browser, usually along with some css and javascript. The browser runs javascript which is able to manipulate the html and do other things, including POSTing data back to the server (where it can be processed by php to generate new html, etc.)

So, in your scenario you run the php on the server to generate html including a form, which is sent back to the browser and displayed to the user. The user puts some stuff in the form and clicks submit. What happens then?

In the default scenario the browser will bundle up the data and ship it back in a POST to whatever url the form specified. This php code:

Code:
<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>

... runs on the server when the form is generated and all it does is point the action of the form back at the same script. It's pretty much boiler plate. So in your case the same script that originally generated the form when a GET request was made, will receive a POST when that form is submitted. This is a pretty common round-trip scenario. It is also why you have:

Code:
if ($_SERVER["REQUEST_METHOD"] == "POST")

... which is there so the script can detect when it is receiving POSTed data, as opposed to receiving a GET request for the initial form.

In this scenario nothing in the way of validation is happening on the browser side. The php script will receive the POSTed data and will then check that data to see if it is complete and compliant. If it is then it will do whatever processing is needed, and either return a new view or redirect the user to a new page.

If the data is not complete and compliant the script will usually regenerate the form markup, repeating the valid data, removing the invalid data, and adding some messaging to the user about what was wrong. This is "server-side" validation and is the simplest round-trip validation scenario for form posts. It's a little old school but it works fine for simple sites.

The next evolutionary step forward is to intercept the form post on the client side and validate the data in javascript. There are a lot of ways to do this, but most people these days will just use a framework like jquery.

Whether you keep your behavior server-side, or want to do client-side validation with javascript, you're going to have to write the code to actually check the data. On the server that will be in php, while on the browser it will be javascript and possibly some framework like jquery.
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
I am with DaveSimmons. Its fairly easy to have it post to the same page and then process the data if its valid:

Code:
// check all posts are valid

if($valid) {
  // do processing of data then redirect
} else {
 //do page markup (html tags)
}
 

fuzzybabybunny

Moderator<br>Digital & Video Cameras
Moderator
Jan 2, 2006
10,455
35
91
I really don't know what I'm doing wrong.

I'm trying to create a session and pass the data to another page automatically.

Code:
<?php 

session_start();
$_SESSION['order-form'] = "sadcfds"; //This is just to test and store whatever
header('Location: nextpage.php'); //The intention is to go to the next page automatically with the session data.

?>

nextpage.php

Code:
<?php
// Print entire contents of form
echo ($_SESSION['order-form']);
?>

Nothing gets echoed. What is going on?
 

Aldon

Senior member
Nov 21, 2013
449
0
0
Code:
<?php 

session_start();
$_SESSION['order-form'] = "sadcfds"; //This is just to test and store whatever
header('Location: nextpage.php'); //The intention is to go to the next page automatically with the session data.

?>

nextpage.php

Code:
<?php
// Print entire contents of form
echo ($_SESSION['order-form']);
?>

Nothing gets echoed. What is going on?


Try:

PHP:
<?php
session_start();

// Print entire contents of form
echo ($_SESSION['order-form']);
?>
 

beginner99

Diamond Member
Jun 2, 2009
5,315
1,760
136
This is "server-side" validation and is the simplest round-trip validation scenario for form posts. It's a little old school but it works fine for simple sites.

The next evolutionary step forward is to intercept the form post on the client side and validate the data in javascript. There are a lot of ways to do this, but most people these days will just use a framework like jquery.

I disagree. Server-side validation isn't old school. In fact it is always required due to the simple fact that request parameters can be manipulated after JavaScript validation. Javascript validation can prevent round trips and increase usability but you should never ever omit server-side validation. It's a security thing (and JavaScript can be disabled).

Try:

PHP:
<?php
session_start();

// Print entire contents of form
echo ($_SESSION['order-form']);
?>

Or in simple words:

session_start();

must be the first line in any php script that wants to use sessions.

@OP

Use google and PHP doc pages. There are so many resource around for PHP. There are multiple ways of doing things.

For this specific problem I prefer to submit the form to a different page. self-submitting php forms are IMHO ugly because then you mix display logic with business logic in one and the same file.

So instead of
PHP:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"

do

PHP:
<form method="POST" action="formProcessor.php"

and but all the code including validation into a new file formProcessor.php. If validation fails, redirect back to the form and keep all form data in the session.

Meaning in formProcessor.php, do something like this:

PHP:
$_SESSION['formData'][myField] = $_POST["myField];

for all submitted data elements. Then redirect back to form with header('Location: myForm.php').

On myForm.php, do as shown below for all input elements:

PHP:
<input id="myField" type="text" name="myField"
            value="<?php echo isset($_SESSION['formData']['myField']) ? htmlentities($_SESSION['formData']['myField']) : ''; ?>" />

So this will basically display the previously submitted, erroneous data again in the correct field.

At the bottom of your form add code similar to

PHP:
if (!empty($_SESSION['Message'])) {

                    echo '<div class="message">' . $_SESSION['Message'] . '</div>';
                    unset($_SESSION['Message']);
                }
                if (!empty($_SESSION['Error'])) {

                    echo '<div class="error">' . $_SESSION['Error'] . '</div>';
                    unset($_SESSION['Error']);
                }

So in your formProcessor you can add

PHP:
$_SESSION['Error'] = "Agent Name is blank";

and after redirecting back to the form that will be displayed on that form.

Note that I use CSS to nicely format this. My css class error:

Code:
.error {
    background: #fff3f3 url(../images/skin/exclamation.png) 4px 50% no-repeat;
    border: 1px solid red;
    color: #cc0000;
    padding: 5px 5px 5px 30px;
    margin-top: 0px;
    margin-left: 15px;
}

To be exact I actually display validation errors directly next to the affected form field. To do this set the validation error on the formProccessor.php:

PHP:
$_SESSION['validationError']['myField'] = "Can't be blank";

And the field look like this on the form:

PHP:
<div>
    <label for="myField">My Field</label>
	<input id="myField" type="text" name="myField"
            value="<?php echo isset($_SESSION['formData']['myField']) ? htmlentities($_SESSION['formData']['myField']) : ''; ?>" />
	<?php
        if(isset($_SESSION['validationError']['myField'])){
                echo "<span id='error'>{$_SESSION['validationError']['myField']}</span>";
        }
     ?>
</div>

Note however that this makes use of CSS. Without the proper CSS it will look like crap.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
I disagree. Server-side validation isn't old school. In fact it is always required due to the simple fact that request parameters can be manipulated after JavaScript validation. Javascript validation can prevent round trips and increase usability but you should never ever omit server-side validation. It's a security thing (and JavaScript can be disabled).

Very good point. I should have said "server-side only."