-1

In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...

php_validation.php

<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"]))  //----------------------------------------------       -------------------------
{
$nameError = "Name is required";
} 
else 
{
$name = test_input($_POST["name"]);  
// check name only contains letters and whitespace
 if (!preg_match("/^[a-zA-Z ]*$/",$name)) 
 {
 $nameError = "Only letters and white space allowed";
 }
 //-----------------------------------------------------------------------

 }
if (empty($_POST["email"])) //----------------------------------------------    -------------------------
{
$emailError = "Email is required";
} 
else 
 {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) 
 {
 $emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"])) 
{
$genderError = "Gender is required";
} 
else 
 {
 $gender = test_input($_POST["gender"]);
 }
 }
function test_input($data) 
{     
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
 }
?>

<h2>PHP Form Validation Example</h2>

<p><span class="error">* required field.</span></p>

<form method="post" name="myForm" action="2222.php"> 

 <p>First Name:
  <input type="text" name="fname"  id="fname" />
  <span class="error">* <?php echo $nameError;?></span>
 </p>
 <br><br>
 <p>
 Email: 
 <input type="text" name="email" id="email">
 <span class="error">* <?php echo $emailError;?></span>
 </p>
 <br><br> 
 <p>  
 Gender:
 <input type="radio" name="gender" value="female">Female
 <input type="radio" name="gender" value="male">Male
 <span class="error">*<?php echo $genderError;?></span><br><br />  
 </p>
 <input class="submit" type="submit" name="submit" value="Submit" >

 </form>
 </body>

2222.php

 <?php
 $name =  $_POST['fname'];
 $email =  $_POST['email'];
 $radio =  $_POST['gender'];

 echo "<h2>Your Input:</h2>";
 echo "user name is: ".$name;
 echo "<br>";
 echo "user email is: ".$email;
 echo "<br>";
 echo "user is ".$radio;
 ?>
Dinesh Gawande
  • 151
  • 2
  • 14
  • If you got error without redirect to `2222.php` you can redirect back to form's page and show error. Like PHPmyadmin does – Manwal Oct 30 '15 at 08:13
  • What is happening and what do you expect to happen in contrast? – Jan Oct 30 '15 at 08:16
  • when you say `directly goes on other page 2222.php` , do you expect your work will be like an ajax? – Drixson Oseña Oct 30 '15 at 08:17
  • when i am clicked on submit button it will redirect on other page where as my all fields are blank and it does not shows any error.. – Dinesh Gawande Oct 30 '15 at 08:25
  • possible duplicate [FORM SUBMIT USING AJAX](http://stackoverflow.com/questions/16616250/form-submit-with-ajax-passing-form-data-to-php-without-page-refresh) – Drixson Oseña Oct 30 '15 at 08:27
  • @Drixson Osena i dont want to use alert message.. i want inline error message if any field is empty or wrong.. it will happens when only form action is blank or itself.. but in my task i have to use another page for answer.. – Dinesh Gawande Oct 30 '15 at 08:34

4 Answers4

1

So I've done a quick code for you :

Here is your "php_validation.php" :

<?php

//Init error var
$nameError = '';
$emailError = '';
$genderError = '';

//Did we have an error ?
if(isset($_GET['error'])){

    //Split error return into an array
    $errorList = explode('_', $_GET['error']);

    //Verify every possible error
    if(in_array('name',$errorList)){
        $nameError = 'Please enter your name<br>';
    }

    if(in_array('email',$errorList)){
        $emailError = 'Please enter your email<br>';
    }

    if(in_array('gender',$errorList)){
        $genderError = 'Please enter your gender';
    }
}


?>

I didnt changed the form

Then this is your "2222.php" :

<?php
$error ='';

function test_input($data) 
    {     
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
 }


//When we receive data
if(isset($_POST)){

    //Verify all possible data and set error
     if(!empty($_POST['fname'])){
        $name =  test_input($_POST['fname']);
     }else{
        $error .= 'name_'; 
     }

     if(!empty($_POST['email'])){
        $email =  test_input($_POST['email']);
     }else{
        $error .= 'email_';
     }
     if(!empty($_POST['gender'])){
        $radio =  test_input($_POST['gender']);
     }else{
        $error .= 'gender_';
     }

     //if we have an error then redirect to form with error
     if(!empty($error)){
        header("Location:php_validation.php?error=".$error);
     }
}
 ?>

Didnt changed your output on this page either.

So as I said previously when you here is what happend when you click the submit button :

  1. Submit Click
  2. Form sent to 2222.php as $_POST and you're redirected to this page

There is no way that could be working if your form is posting on an other page than the one where the check is made.

Nirnae
  • 1,315
  • 11
  • 23
0

Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.

If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php

Nirnae
  • 1,315
  • 11
  • 23
  • actually my prob is when any field is empty or wrong it does not to show inline errror message when hiting submit button.. and page redirect to 2222.php – Dinesh Gawande Oct 30 '15 at 08:40
  • Yeah, as I said, the form is submitted and you error check isn't executed as the page is automatically redirect to 2222.php and isn't doing anything else from "php_validation.php" except sending a $_POST var, try switching your check to 2222.php and you should get your errors – Nirnae Oct 30 '15 at 08:44
  • sorry but nothing can happend when use validation code on 2222.page – Dinesh Gawande Oct 30 '15 at 08:57
0

You could do one of the following things:

  1. Do all the checking in Javascript "onClick" function

  2. Do Ajax call "onClick" to a handler page, get the validation message from that page.

  3. Do the validation on "2222.php" page

  4. action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page

Now depends only on you which fits your program.

Edwin
  • 2,146
  • 20
  • 26
0

If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.

Example:

files:

  • file-with-form.php
  • form-submit-processing-file.php

Code examples:

file-with-form.php

<!DOCTYPE html>
<html>
<head>
    <title>[Your page title]</title>
</head>
<body>
    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field.</span></p>

    <!-- Form -->
    <form action="[path-to-form-submit-process]" method="[GET|POST]" 
          target="form-processor">
        <div>
            <label>First Name:
                <input type="text" name="fname"  id="fname" />
                <span class="error">* <?php echo $nameError ?></span>
            </label>
        </div>
        <div>
            <label>Email:
                <input type="text" name="email" id="email">
                <span class="error">* <?php echo $emailError ?></span>
            </label>
        </div>
        <div>
            <label>Gender:
                <p><input type="radio" name="gender" value="female"> Female</p>
                <p><input type="radio" name="gender" value="male"> Male</p>
                <p><span class="error">*<?php echo $genderError ?></span></p>
            </label>
        <input class="submit" type="submit" name="submit" value="Submit" >
        </div>
    </form>

    <!-- The iframe to submit the form to -->
    <iframe name="form-processor" id="form-processor" 
            src="[path-to-form-submit-process]"></iframe>

    <!-- 
    NOTE: The error message spans are left there just because you had them 
    in your code, those will not work here at this point, actually depending 
    on your php configuration will most probably throw errors/warnings, 
    because such variables were not defined at all...
    -->
</body>
</html>

As:

  • [path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
  • [*] - placeholders that should be replaced with the values for your case

form-submit-processing-file.php

<?php 

# Processing the form fields and displaying the messages
$post = $_POST;

# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable

# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];

function addErrorMessage($message, &$messages, &$errorFlag)
{
    $errorFlag = true;
    $errorMessageTemplate = '<p class="error-message">{message}</p>';
    array_push($messages, str_replace('{message}', $message, 
        $errorMessageTemplate));
}

// Validating the email
$email = array_key_exists('email', $post) 
    ? $post['email']
    : null;

if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    // Raising the flag for an error on validation
    addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}

// ........
// validation of rest of fields
// ........

$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
    // ........
} catch (Exception $e) {
    $internalError = true;
}

# Stop execution on internal error
if ($internalError === true) 
{ 
    ?>
    <h2>Sorry, there's an error on our side... we'll do all in our 
        powers to fix it right away!</h2>
    <?php
    exit;
}

# Displaying the results
if ($invalidFormData === true) {
    // Building errors message
    $messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
    $messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}

// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);

// Displaying the messages:
echo implode('', $messages);

However I believe this should be done via an AJAX call insted. Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)