display alert when form is submitted - php

I need to display the alert saying thanx your msg is received but this doesnot works so please hel me out how to do.Is there coding error or what i coudnt get to it.i would pe pleased if someone helps me out.thankyou
<h4>Send Your Feedback Here.<p>
<form name ="register" action="contact.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="validate()">Send</button>
</p>
</form>
<script type="text/javascript">
function validate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y)
{
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="")
{
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="")
{
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="")
{
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="")
{
alert(msg);
}
else
{
<?php
//Get message data.
$name = $_POST['name'];
$message = $_POST['message'];
$email=$_POST['email'];
$ver = $_POST['ver'];
$rval = $_POST['rval'];
if($ver==$rval)
{
//Email it.
mail(
'example#example.com', //Where to send
"Contact form - $name", //Email subject
$message, //Message body
$email //email address
);
echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>";
}
else
{
echo "<script type=\"text/javascript\">alert('Wrong captcha');</script>";
}
?>
}
}

You can't mix JavaScript and PHP like that. The PHP will be parsed on the served before the page is served up to the user. Including it inside of your JavaScript else block will have no effect, since the code will be run when the page is generated anyway.
You should look into the use of AJAX.

<script type="text/javascript">
function thevalidate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y) {
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="") {
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="") {
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="") {
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="") {
alert(msg);
} else {
<?php
//You need to process data here..
?>
}
}
</script>
<h4>Send Your Feedback Here.<p>
<form name ="register" action="php/process.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="thevalidate()">Send</button>
</p>
</form>

Related

php input form can only be numbers not words

i made a form where you can put a number and show which one is the highest.
i want to make sure you can put any words in this form.
that there show a notification you cant put words in the form
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="text" name="tweedegetal" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
The following code shows a notification when a letter is typed.
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" id="eerstegetal" name="eerstegetal" oninput="Eerste_check()" placeholder="Eerste getal"><br>
<input type="text" id="tweedegetal" name="tweedegetal" oninput="Tweede_check()" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script>
function Eerste_check(){
var eerstegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(eerstegetal)){
alert('Eerstegetal should contain only numbers.')
}
}
function Tweede_check(){
var tweedegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(tweedegetal)){
alert('Tweedegetal should contain only numbers.')
}
}
</script>
Try the following:
<input type="number" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="number" name="tweedegetal" placeholder="Tweede getal"><br>
I hope it helps

PHP echoing JQuery on failed form submit

I'm working on a signup form in PHP. The form is a div which opens when you click on a button. Here's my code:
if(!$fieldsFilled){
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
This all executes after my form is submitted:
if (isset($_POST['signUp']))
Full PHP code:
<?php require 'dbconnect.php'; ?>
<?php
//Error message variable declarations
$unmatchedPasswordsError = "";
$unfilledFormsError = "";
$emailError = "";
//If sign up submit POST recieved
if (isset($_POST['signUp']))
{
//Start session
session_start();
$email = $connection->real_escape_string($_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows)
{
$emailInUse = true;
}
else
{
$emailInUse = false;
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suVerifyPassword', 'suDisplayName');
$fieldsFilled = true;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$fieldsFilled = false;
}
else
{
$fieldsFilled = true;
}
}
if ($emailInUse)
{
$emailError = "The email is already in use.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
if(!$fieldsFilled)
{
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "The email is not valid.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Check for unverified password
if ($_POST['suPassword']!= $_POST['suConfirmPassword'])
{
$unmatchedPasswordsError = "The passwords do not match.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Variable declaration for sign up POST values
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//Insert POST values into database
$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
//Redirect to 'email sent' webpage
header('Location: emailSent.php');
}
}
}
}
}
//If log in submit POST recieved
if (isset($_POST['logIn']))
{
//Variable declaration for log in POST values
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//Search for log in credentials in dabase
$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
//TODO: CHECK FOR REMEMBER ME CHECK
session_start();
$_SESSION['userID'] = $row['userID'];
}?>
HTML sign up div/form code:
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<?php
echo '<br><font class="text-error" id="email-error">',$emailError,'</font>';
?>
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<?php
echo '<br><font class="text-error" id="passwords-unmatched-error">',$unmatchedPasswordsError,'</font>';
?>
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<?php
echo $unfilledFormsError;
?>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
The "test passed" does log to the console, however the div is not showing after the page refresh (due to form submission). Any help is appreciated! Thank you so much!
I have customized as your requirement and database connection i have used
Mysqli replace whatever you want also change database credentials.
Full code will be in same page. Try and comment if you don't understand anything.
<?php
session_start();
//require 'dbconnect.php';
$connection=mysqli_connect("localhost","root","","test"); // I have use it for testing
$errors = array();
if (isset($_POST['signUp'])) {
$email = mysqli_real_escape_string($connection, $_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
//email check
if(mysqli_num_rows($result)>0){
$errors[] = "The email is already in use.";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "The email is not valid.";
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suConfirmPassword', 'suDisplayName');
foreach($required as $field){
if (empty($_POST[$field])){
$errors[] = $field." Cannot be empty.";
}
}
if(count($errors)==0){
if($_POST['suPassword']!=$_POST['suConfirmPassword']){
$errors[] = "The passwords do not match.";
}else{
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
$sql = mysqli_query($connection, "INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
if($sql){
header('Location: emailSent.php');
}else{
$errors[] = "Failed to insert.";
}
}
}
}
if (isset($_POST['logIn'])){
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$result = mysqli_query($connection, "select * from users where email = '$liEmail' AND password = '$liPassword'");
if($result){
$row = mysqli_fetch_assoc($result);
$_SESSION['userID'] = $row['userID'];
}
}
?>
<?php
if(!empty($errors)){
foreach ($errors as $value) {
echo "<span style='color:red;'>".$value."</span><br>";
}
}
?>
<button type="button" id="showSignup">Show Sign-up</button><br><br>
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
<?php if(isset($_POST['signUp']) && count($errors)>0){ ?>
$('#home-sign-up-box').show();
<?php }elseif(isset($_POST['signUp']) && count($errors)==0){ ?>
//$('#home-sign-up-box').hide();
<?php }else{?>
//$('#home-sign-up-box').show();
<?php }?>
$("#showSignup").click(function(){
$('#home-sign-up-box').toggle();
visible_check();
});
visible_check();
});
function visible_check(){
var isVisible = $( "#home-sign-up-box" ).is( ":visible" );
if(isVisible){
$("#showSignup").html("Hide Sign-up");
}else{
$("#showSignup").html("Show Sign-up");
}
}
</script>

Why this validation code does not work as expected?

I have a form and the action of the for m is same page.
I am trying to :
Show a thanks message upon the successful form submission
Show error messages next to the field where the error is detected
All the above must be shown in the same page.
My code is :
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
else {
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
?>
I've limited the validation and showing only for first part in this QUESTION.
When I submit this form If there is NO any errors the I am getting the message Thanks, We have received your feed back
That's fine and works as expected.
When an error exists / the field Guest name is empty I am getting the message during the form submission Errors!
Please check the fields which have errors below. Error hints are in Red.
That's also fine.
But my form is just disappear when I get the above message. Why?
Also I want show that Please type your name! next to the field.
Try bellow code. I have removed else part and set flag with true/false to check from is valid or not.
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
$chkValidate = "true";
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
$chkValidate = "false";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';
$chkValidate = "false";
}
if($chkValidate == "true"){
echo 'Thanks, We have received your feed back';
}
}
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?php if(!empty($errors) && $chkValidate != "false") { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
?>
Just remove else condition cause actually your form will not be display if $_POST["Ask_the_Question"] is set
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
The reason why is here:
<?php
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
} else {
// your form code will never be called if $_POST['Ask_the_Question'] is set
TO do what you want to achieve you probably want to do something like this instead:
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
} else { ?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
}
?>
Other answers are fine, but just to clarify what happens.
But my form is just disappear when I get the above message. Why?
Your form disappear because if you pass the first if you can't get to your else.
if (isset($_POST["Ask_the_Question"])) {
...
} else {
xxx;
}
That means if you want to see your form you have to put it somewhere it can be shown like elseif (with more restrictions), or ifs inner or outer.
if (isset($_POST["Ask_the_Question"]) && empty($errors)) {
...
} elseif (isset($_POST["Ask_the_Question"]) && !empty($errors)) {
...
} else {
...
}
Also I want show that Please type your name! next to the field.
To show all errors you could use eg. foreach anywhere you want to show them.
foreach ($errors as &$error) {
echo "Error: $error<br />\n";
}
Btw be careful with the empty(); function.

Why isn't my php form passing the data

here is my code. I am not sure why after i input the first and last name the second page does not show the proper text.. The form is suppose to take in first name and last name into a text box.. Then on the next page when person submits it should validate that the proper type of data was input, and then print out text if it was not, or print out text if it was successful.
<body>
<h2 style="text-align:center">Scholarship Form</h2>
<form name="scholarship" action="process_Scholarship.php" method="post">
<p>First Name:
<input type="text" name="fName" />
</p>
<p>Last Name:
<input type="text" name="lName" />
</p>
<p>
<input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send Form" />
</form>
my second form
<body>
<?php
$firstName = validateInput($_POST['fName'],"First name");
$lastName = validateInput($_POST['lName'],"Last name");
if ($errorCount>0)
echo <br>"Please use the \"Back\" button to re-enter the data.<br />\n";
else
echo "Thank you for fi lling out the scholarship form, " . $firstName . " " . $lastName . ".";
function displayRequired($fieldName)
{
echo "The field \"$fieldName\" is required.<br />n";
}
function validateInput($data, $fieldName)
{
global $errorCount;
if (empty($data))
{
displayRequired($fieldName);
++$errorCount;
$retval = "";
}
else
{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
$errorCount = 0;
?>
</body>

PHP questionnaire strategy

I am designing a questionnaire, the code I've written is a combination of JS and PHP. I have the questions in one page but I want to ask each question on a separate page and the consecutive questions should be asked according to the answer the user select. what is the best strategy to do that? do I need to include SQL as well?
and at the end the answers will be written in a text file
the code I have is:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['name']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
$varName = $_POST['name'];
$varLand1 = $_POST['landscape1']; $varLand2 = $_POST['landscape2'];
$varCom = $_POST['comment'];
$varAppx = $_POST['appx'];
$clim = $_POST['landscape'];
$varMech = $_POST['mechanism'];
$varMechoth = $_POST['mech'];
if(empty($errorMessage))
{
$fs = fopen("$varName.txt" ,"a+");
fwrite($fs,$varName . "\n" . $varLand1 . ' ' .$varLand2 . "\n" . $clim . "\n" . $varAppx . "\n" . $varCom . "\n" . $varMech .$varMechoth);
fclose($fs);
header("Location: t-y.html");
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script scr="jss.js" type="text/javascript"></script>
<title>Questionnaire</title>
</head>
<body>
<FONT FACE="Times New RomanPS">
<H1>Questionnaire</H1>
<P>Please fill out this questionnaire:
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="index.php" method="post">
<p>
Name<br>
<input type="text" name="name" maxlength="50" value="<?=$varName;?>" />
</p>
<ul>
<p> 1 - Q1?
<p><input type="checkbox" name="landscape1" value="urban"> Urban<br>
<p><input type="checkbox" name="landscape2" value="non-urban"> non-Urban<br>
<p> 2 - Q2?<br>
<input type="radio" name="landscape" value="Dry"> Dry<br>
<input type="radio" name="landscape" value="Tropical"> Tropical<br>
<input type="radio" name="landscape" value="Moderate"> Moderate<br>
<input type="radio" name="landscape" value="Continental"> Continental<br>
<input type="radio" name="landscape" value="Polar"> Polar<br>
<p> 3 - Q3? <br>
<input type="radio" id="mecha" name="mechanism" value="sub" onclick="hideTextBox1()"/> Subsidence<br>
<input type="radio" id="mecha" name="mechanism" value="earth" onclick="hideTextBox1()"/> Earthquake<br>
<input type="radio" id="mecha" name="mechanism" value="volc" onclick="hideTextBox1()"/> Volcanic<br>
<input type="radio" id="mecha" name="mechanism" value="<?=$varMech;?>" onclick="displayTextBox1()"/> other<br>
<div id="otherTextBox1" style="display:none;visibility:hidden;">
<input type="text" name="mech" maxlength="20" value="<?=$varMech;?>">
</div>
<p> 4 - Q3?<br>
<input name="choice" id="choice4" type="radio" value="four" onclick="hideTextBox()"/><label for="choice4"> No </label><br>
<input name="choice" id="choice5" type="radio" value="other" onclick="displayTextBox()"/><label for="choice5"> Yes </label>
<br/>
<div id="otherTextBox" style="display:none;visibility:hidden;">
[mm/yr]<br><input type="text" name="appx" maxlength="3" value="<?=$varAppx;?>">
</div>
<br/>
<p> 5 - Q4
<p> 6 - Q5
<p> 7 - Q6
<p>
Comments:<br>
<textarea type="text" name="comment" cols=48 rows=4 maxlength="1000" value=" <?=$varComment;?>"></textarea>
</p>
<p><input type="reset"> <input type="submit" name="formSubmit" value="Submit" />
</ul>
<script>
function displayTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'block';
otherTextBox.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'none';
otherTextBox.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('choice');
var objElement;
var boolContinue = false;
var objOtherText;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'choice5')
{
objOtherText = document.getElementById('othertext');
if(strTrim(objOtherText.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
function displayTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'block';
otherTextBox1.style.visibility = 'visible';
}
function hideTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'none';
otherTextBox1.style.visibility = 'hidden';
}
function validate1()
{
var arrElements1 = document.getElementsByName('mechanism');
var objElement1;
var boolContinue = false;
var objotherText1;
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else<?=$varMech;?>
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* #param: {String} String to trim.
*
* #return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
</script>
</form>
</FONT>
</body>
</html>
I don't think you would NEED to use SQL to do this. You should be able to use the $_SESSION to store the answers to previous questions and adjust the questions on the following pages accordingly.

Categories