Reputation: 622
I'd like to know if it is possible to manage error if in the form, action is set to another script.
ajoutDevis.php
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<span class="error">* <?php echo $clientErr;?></span>
</FORM>
ajoutDevisScript.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['client'])) {
$clientErr = "ERROR";
} else $client = $_POST['client'];
So, is it possible to display my error in the span if the input is empty ? Or there is no way doing it with an other script as action ?
Thanks!
Upvotes: 1
Views: 815
Reputation: 1
Yes, it is possibile with $_SESSION
variables to store values during the session and header()
function to redirect user from the second script back to the first.
Supposing both files are in the root directory, ajoutDevis.php:
<?php
session_start();
?>
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<?php if (isset($_SESSION['clientErr'])) : ?>
<span class="error">* <?php echo $_SESSION['clientErr'] ?></span>
<?php endif; ?>
</FORM>
and ajoutDevisScript.php:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['client'])) {
$_SESSION['clientErr'] = "ERROR";
header('Location: ajoutDevis.php');
} else {
$client = $_POST['client'];
}
}
?>
I would suggest you to print the span
only if you need to. I would also suggest you to check your brackets to avoid PHP errors.
Upvotes: 0
Reputation: 588
You need to do the following:
Add the form code as well on the ajoutDevisScript.php page at the bottom of page.
<?php if(!empty($clientErr)) { ?>
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<span class="error">* <?php echo $clientErr;?></span>
</FORM>
<?php } ?>
This will check if there is any error in error variable it will display the form on same page with error.
Upvotes: 0
Reputation: 481
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['client'])) {
$clientErr = "ERROR";
$_SESSION['error] = $clentErr;
header('location:ajoutDevis.php');
} else $client = $_POST['client'];
In your ajoutDevis.php file
session_start();
$clientErr = ($_SESSION['error']!='')?$_SESSION['error']:'';
<FORM name='devis' method='POST' action='ajoutDevisScript.php' id='form'>
<label for="client">Client</label>
<input type='text' id='client' name='client'>
<span class="error">* <?php echo $clientErr;?></span>
</FORM>
Upvotes: 1