Captcha code used to sign up form is not working - javascript

I would to like to create a sign up form using Captcha in php with mysql data. Anytime I submit the form, the Captcha code shows an error. But when I check my database connecting code is working. The code is below.
signup.php
<?php
session_start();
?>
<!DOCTYPE html>
enter code here<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Registration Form with PHP Captcha Demo</title>
<meta name="title" content="Registration Form with PHP Captcha Demo"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<link href="css/style_demo.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$(".refresh").click(function () {
$(".imgcaptcha").attr("src","demo_captcha.php?_="+((new Date()).getTime()));
});
$('#register').submit(function() {
if($('#password').val() != $('#cpassword').val()){
alert("Please re-enter confirm password");
$('#cpassword').val('');
$('#cpassword').focus();
return false;
}
$.post("submit_demo_captcha.php?"+$("#register").serialize(), { }, function(response){
if(response==0){
$(".imgcaptcha").attr("src","demo_captcha.php?_="+((new Date()).getTime()));
clear_form();
alert("Data Submitted Successfully.")
}else{
alert("wrong captcha code!");
}
});
return false;
});
function clear_form()
{
$("#fname").val('');
$("#lname").val('');
$("#username").val('');
$("#email").val('');
$("#dob").val('');
$("#gender").val('');
$("#password").val('');
$("#cpassword").val('');
$("#captcha").val('');
}
});
</script>
</head>
<body>
<div id="bodyfull">
<div id="bodyfull2">
<div id="center">
<div class="inner_right_demo">
<form name="register" action="#null" method="post" id="register">
<div class="form_box">
<div>
<label>First Name</label>
<input type="text" placeholder="Enter Your First Name" id="fname" name="fname" required="required">
</div>
<div>
<label>Last Name</label>
<input type="text" placeholder="Enter Your Last Name" id="lname" name="lname" required="required">
</div>
<div>
<label>User Name</label>
<input type="text" placeholder="Enter Your User Name" id="username" name="username" required="required">
</div>
<div>
<label>Email</label>
<input type="email" placeholder="Enter Your Email Address" id="email" name="email" required="required">
</div>
<div>
<label>Date of birth</label>
<input type="date" id="dob" name="dob">
</div>
<div>
<label>Gender</label>
<div class="otherinputs"><input type="radio" value="Male" checked name="gender"> <span>Male</span> <input type="radio" value="Female" name="gender"> <span>Female</span> </div>
</div>
<div>
<label>Password</label>
<input type="password" placeholder="Enter Your Password" id="password" name="password" required="required">
</div>
<div>
<label>Confirm Password</label>
<input type="password" placeholder="Enter Your Password Again" id="cpassword" name="cpassword" required="required">
</div>
<div>
<label>Captcha</label>
<input type="text" placeholder="Enter Code" id="captcha" name="captcha" class="inputcaptcha" required="required">
<img src="demo_captcha.php" class="imgcaptcha" alt="captcha" />
<img src="images/refresh.png" alt="reload" class="refresh" />
</div>
<div>
<label> </label>
<div class="otherinputs" ><input type="submit" value="Submit" name="B1" class="submit"> </div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
demo_captcha.php
<?php
session_start();
function getRandomWord($len = 5) {
$word = array_merge(range('0', '9'), range('A', 'Z'));
shuffle($word);
return substr(implode($word), 0, $len);
}
$ranStr = getRandomWord();
$height = 35; //CAPTCHA image height
$width = 150; //CAPTCHA image width
$font_size = 24;
$image_p = imagecreate($width, $height);
$graybg = imagecolorallocate($image_p, 245, 245, 245);
$textcolor = imagecolorallocate($image_p, 34, 34, 34);
imagettftext($image_p, $font_size, -2, 15, 26, $textcolor, 'fonts/mono.ttf', $ranStr);
//imagestring($image_p, $font_size, 5, 3, $ranStr, $white);
$_SESSION["vercode"] = $ranStr;
imagepng($image_p);
imagedestroy($image_p);
?>
submit_demo_captcha
<?php
session_start();
$servername="localhost";
$username="root";
$password="1234";
$dbname="form";
$con=mysqli_connect($servername,$username,$password,$dbname);
if(($_REQUEST['captcha'] == $_SESSION['vercode'])){
$lname =$_POST['lname'];
$fname = $_POST['fname'];
$gender = $_POST['gender'];
$username =$_POST['username'];
$email =$_POST['email'];
$dob =$_POST['dob'];
$password =$_POST['password'];
//Here you can write your sql insert statement.
$sql = "INSERT INTO form.form1 (fname,gender,lname,mname,email,dob,password) VALUES('$fname','$gender','$lname','$username','$email','$dob','$password')";
if(mysqli_query($con,$sql)){
alert("Data Submitted Successfully.");
}
else{
alert("wrong captcha code!");
}
}
mysqli_close($con);
?>

submit_demo_captcha.php
<?php
session_start();
$servername="localhost";
$username="root";
$password="1234";
$dbname="form";
$con=mysqli_connect($servername,$username,$password,$dbname);
if(($_REQUEST['captcha'] == $_SESSION['vercode'])){
$lname =$_REQUEST['lname'];
$fname = $_REQUEST['fname'];
$gender = $_REQUEST['gender'];
$username =$_REQUEST['username'];
$email =$_REQUEST['email'];
$dob =$_REQUEST['dob'];
$password =$_REQUEST['password'];
//Here you can write your sql insert statement.
$sql = "INSERT INTO form.form1 (fname,gender,lname,mname,email,dob,password) VALUES('$fname','$gender','$lname','$username','$email','$dob','$password')";
if(mysqli_query($con,$sql)){
echo 1; }
else{
echo 0; }
}
mysqli_close($con);
?>
and
signup.php
$.post("submit_demo_captcha.php?"+$("#register").serialize(), { }, function(response){
if(response==1){
$(".imgcaptcha").attr("src","demo_captcha.php?_="+((new Date()).getTime()));
clear_form();
alert("Data Submitted Successfully.")
}else{
alert("wrong captcha code!");
}
});

Related

Form Submit with using Jquery Ajax PHP

I know there is a lot of similar questions but I am working on this exact same problem for two days and I just gave up.
So after the form is submitted, I want to prevent the current page (updates.php) to redirect to another page (test.php).
I am trying to do this with Jquery Ajax, but in this point, I am open to any solution.
updates.php:
<form action="test.php" method="post">
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary">
</div>
</form>
test.php:
<?php
$id = $_POST['id'];
$username = $_POST['name'];
$comment = $_POST['subject'];
if(!empty($username) || !empty($comment))
{
$conn = mysqli_connect('localhost','Admin','admin123','website');
if(!$conn)
{
echo "Connection Error: " . mysqli_connect_error();
}
else
{
$INSERT = "INSERT INTO comments (id, name, comment) VALUES (?,?,?)";
$stmt = $conn -> prepare($INSERT);
$stmt -> bind_param("iss", $id, $username, $comment);
$stmt -> execute();
}
}
else { echo "All fields are required"; die();}
?>
Whatever I did I couldn't stop test.php to open.
Try this as your updates.php file instead:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function submitWithAjax(){
var name = document.getElementById("name").value;
var id = document.getElementById("id").value;
var subject = document.getElementById("subject").value;
$.post( "test.php", {name: name, id: id, subject: subject})
.done(function(data) {
alert( "Data Loaded: " + data );
});
}
</script>
</head>
<body>
<form>
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Name:" required>
</div>
</div>
<input type = "hidden" id="id" name = "id" value = "4" />
<div class="row form-group">
<div class="col-md-12">
<label class="sr-only" for="subject">Comment</label>
<input type="text" name="subject" id="subject" class="form-control" style="background:white;opacity:.5;border:none;" placeholder="Write a comment..." required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Post Comment" class="btn btn-primary" onclick="event.preventDefault();submitWithAjax();">
</div>
</form>
</body>
</html>

Getting user inputs from HTML form

I want to be able to get the inputs that a user enters in my HTML form and be able to print them later on my website. I would love to be able to print all the user info with the selections they have made to there pizzas. I have been trying for the last few hours to do this and no luck :( Looking to get the date, first name, last name, address and phone.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Daves Pizza</title>
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="pizza.js"></script>
</head>
<body>
<div align="center">
<h5>Today is: <span id="dtfield"></span></h5>
</div>
<br>
<div align="center">
<h1>Dave's Pizza Place</h1>
</div>
<div align="center">
<div class="user">
<form id="contact_form" action="mailto: david.genge#edu.sait.ca" name="userInfo" method="POST" enctype="text">
<br>
<div>
<label for="datetime">Date:</label>
<input type="date" name="user_date" />
</div>
<div>
<label for="firstname">Firstname:</label>
<input type="text" pattern="[A-Za-z-']+" name="firstname" value="Firstname" maxlength="20"/>
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" pattern="[A-Za-z-']+" name="lastname" placeholder="Lastname" maxlength="20"/>
</div>
<div>
<label for="mail">Address:</label>
<input type="text" name="user_mail" placeholder="Full Address"/>
</div>
<div>
<label for="tel">Phone#:</label>
<input type="tel" pattern="[0-9]+"" name="user_phone" placeholder="(403)123-1234"/>
</div>
</form>
</div>
</div>
<div align="center">
<div class="pizza">
<form name="costEstimation">
<table border="0">
<tr valign="middle">
<td>
<br>
<b>Choose Your Pizza Type<b><br>
<input type="radio" name="pizzasize" value="8" checked>Small $8<br>
<input type="radio" name="pizzasize" value="10">Medium $10<br>
<input type="radio" name="pizzasize" value="15">Large $15<br>
<input type="radio" name="pizzasize" value="18">Extra Large $18<br></td>
<td></td>
</tr>
<tr>
<td>
<b>Specialities<b><br>
<input type="radio" name="special" value="3">Super Cheesy $3<br>
<input type="radio" name="special" value="5">Extra Meaty $5<br>
<input type="radio" name="special" value="2">Really Veggie $2<br></td>
<td>
<b>Extra Toppings </b>
<br>
<input type="checkbox" name="cheese" value="1.5">Extra Cheese $1.50<br>
<input type="checkbox" name="pepperoni" value="1.5">Pepperoni $1.50<br>
<input type="checkbox" name="mushrooms" value="1.5">Mushrooms $1.50<br>
<input type="checkbox" name="bacon" value="1.5">Bacon $1.50<br>
<input type="checkbox" name="olives" value="1.5">Olives $1.50<br>
</td>
</tr>
</table>
</form>
<h2>Pizza Cost: </h2><h2><span id="result"></span></h2>
<input type=button value="Price Your Pizza" onClick="pizza(); return false;">
<button type="submit">Send your message</button>
<br><br><br>
<table>
<tr>
<td>
<figure>
<center>
<img src="cheese.jpg" alt="cheese" height="100" width="100">
</center>
</figure>
</td>
<td>
<figure>
<center>
<img src="veg.jpg" alt="veg" height="100" width="100">
</center>
</figure>
</td>
<td>
<figure>
<center>
<img src="meat.jpg" alt="meat" height="100" width="100">
</center>
</figure>
</td>
</tr>
</table>
</div>
<br>
<br>
<br>
</div>
</body>
</html>
You need to use form for saving the input values entered by user. you can do it by either GET or POST method. here is the sample demo with Validation:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "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" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
you need to use any server side language to get input from user.
Use this statement
<form method="GET or POST" action="file_location/file_name(on which you want to get input)">
Php is very simple language you can learn it easly
i am giving you an example:
index.html
<form method="GET" action="localhost://getdata.php">
<input type="text" name="UserName" />
<input type="button" value="Submit" />
</form>
Focus on name tag i used in input statement "UserName" your data will be send by binding user input in it and then you can display data using php with this name as showing below
getdata.php
<?php
echo "$_GET['UserName']";
?>
if you want to get the data using javascript then,
HTML:
<input type="text" name="name" id="uniqueID" value="value" />
<span id="output"></span>
JS:
var nameValue = document.getElementById("uniqueID").value;
document.getElementById("output").innerHTML=nameValue;
will work for you !

Input type="file" somehow prevent the JS-made inputs' value from being sent via POST

Good day, as the title states, the values of the inputs created by JavaScript are not being sent via POST(or even via GET, the name of the inputs does not appear).
I managed to discover the culprit by excluding the input type="file" from the form, then trying to send it again via POST(and via GET too). Both method retrieved the values of those JS-made inputs.
UPDATE AGAIN
Here's the standalone culprit code:
<?php
if (isset($_POST['newEmpSubmit'])) {
echo 'Emp Last Name '.$_POST['empLastName'].'<br/>';
echo 'Emp First Name '.$_POST['empFirstName'].'<br/>';
echo 'Emp Middle Name '.$_POST['empMiddleName'].'<br/>';
echo 'Emp Address '.$_POST['empAddress'].'<br/>';
echo 'Emp BirthDate '.$_POST['empBirthDate'].'<br/>';
echo 'Emp Nationality '.$_POST['empNationality'].'<br/>';
echo 'Emp Gender '.$_POST['empGender'].'<br/>';
echo 'Emp SSS '.$_POST['empSSS'].'<br/>';
echo 'Emp TIN '.$_POST['empTIN'].'<br/>';
echo 'Emp Philhealth '.$_POST['empPhilhealth'].'<br/>';
echo 'Emp Department '.$_POST['empDepartment'].'<br/>';
echo 'Emp Phone '.$_POST['empPhone'].'<br/>';
$chosenFinal = $_POST['chosenIDFinal'];
$chosenInfo = $_POST['chosenIDInfo'];
$totalIDCount = count($chosenFinal);
for ($i=0; $i < $totalIDCount; $i++) {
$finalChosenArray[] = $chosenFinal[$i].'('.$chosenInfo[$i].')';
}
$chosenIDString = implode(', ', $finalChosenArray);
echo $chosenIDString.'<br>';
echo 'Emp Marital Status '.$_POST['empMaritalStatus'].'<br/>';
if ($_POST['empMaritalStatus'] == 'Married') {
echo 'Spouse Last Name '.$_POST['spouseLastName'].'<br/>';
echo 'Spouse First Name '.$_POST['spouseFirstName'].'<br/>';
echo 'Spouse Middle Name '.$_POST['spouseMiddleName'].'<br/>';
echo 'Number of children '.$_POST['numOfChildren'].'<br/>';
echo 'Spouse Contact '.$_POST['spouseContactNo'].'<br/>';
echo 'Spouse Address '.$_POST['spouseAddress'].'<br/>';
}
echo 'Emergency Last Name '.$_POST['emergencyLname'].'<br/>';
echo 'Emergency First Name '.$_POST['emergencyFname'].'<br/>';
echo 'Emergency Middle Name '.$_POST['emergencyMname'].'<br/>';
echo 'Emergency Phone '.$_POST['emergencyPhone'].'<br/>';
echo 'relationship '.$_POST['relationship'].'<br/>';
echo 'Emp qualification '.$_POST['empQualification'].'<br/>';
echo 'Emp Certification '.$_POST['empCertification'].'<br/>';
echo 'Emp Last Employer '.$_POST['empLastEmp'].'<br/>';
echo 'Emp Overall '.$_POST['empOverall'].'<br/>';
echo 'Emp Hired Date '.$_POST['hiredDate'].'<br/>';
echo 'Emp Salary '.$_POST['empSalary'].'<br/>';
echo 'Emp Salary Type '.$_POST['salaryType'].'<br/>';
echo 'Emp Benefits '.$_POST['empBenefits'].'<br/>';
echo 'Emp Tax Amount '.$_POST['empTaxAmount'].'<br/>';
echo 'Emp SSS Amount '.$_POST['empSSSAmount'].'<br/>';
echo 'Emp Philhealth Amount '.$_POST['empPhilhealthAmount'].'<br/>';
echo 'Emp Status '.$_POST['empStatus'].'<br/>';
echo 'Emp Highest Edu '.$_POST['empHighestEdu'].'<br/>';
echo 'Emp Institution '.$_POST['empInstitution'].'<br/>';
echo 'Emp Course '.$_POST['empCourse'].'<br/>';
echo 'Emp Awards '.$_POST['empAwards'].'<br/>';
echo 'Emp Grad Year '.$_POST['empGradYear'].'<br/>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Theme Template for Twitter Bootstrap</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Bootstrap theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js does not work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="modal fade" id="validIDModal" tabindex="-1" role="dialog" aria-labelledby="modalTitle">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalTitle" style="text-align:center;">
VALID IDs
</h4>
</div>
<div class="modal-body">
<div class="row">
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Driver's ID">
Driver's ID
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Government's ID">
Government's ID
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Passport ID">
Passport ID
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="PRC ID">
PRC ID
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="NBI Clearance">
NBI Clearance
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Police Clearance">
Police Clearance
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Postal ID">
Postal ID
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Voter's ID">
Voter's ID
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Brgy. Certification">
Brgy. Certification
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="GSIS">
GSI
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="Diploma">
Diploma
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="OWWA">
OWWA
</label>
<label class="col-md-4">
<input type="checkbox" name="chosenID[]" value="OFW ID">
OFW
</label>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="submit" data-dismiss="modal" onclick="addValidID()">ADD IDs</button>
</div>
</div>
</div>
</div>
<div id="content-wrapper">
<div class="uploadimg">
<form action="" method="POST" enctype="multipart/form-data">
Upload Profile Image:<br/>
<input type="file" name="profile_photo" />
<br>
</div>
<div>
<div>
<div>
<div >
<h3><b>ADD EMPLOYEE</b></h3>
</div>
</div>
<div >
<div>
<b>Personal Details</b>
</div>
<div>
<div>
<input type="text" name="empLastName" placeholder="Last Name" required><br/>
<input type="text" name="empFirstName" placeholder="First Name" required><br/>
<input type="text" name="empMiddleName" placeholder="Middle Name" required><br/>
<input type="text" name="empAddress" placeholder="Residential Address" required><br/>
<label for="birthDate">
Birth Date
<input id="birthDate" type="date" name="empBirthDate" placeholder="Date of Birth" required>
</label><br/>
<input type="text" name="empNationality" placeholder="Nationality" required><br/>
<input type="email" name="empEmail" placeholder="E-mail Address" required><br/>
<label>
Gender<br>
<label >
<input type="radio" name="empGender" value="Male" checked required>
Male
</label><br/>
<label >
<input type="radio" name="empGender" value="Female" required>
Female
</label>
</label><br/>
<input type="text" name="empSSS" placeholder="SSS Number" required><br/>
<input type="text" name="empTIN" placeholder="TIN Number" required><br/>
<input type="text" name="empPhilhealth" placeholder="PhilHealth Number" required><br/>
<input type="text" name="empPhone" placeholder="Phone/Contact Number" required><br/>
<b>ADD VALID IDs</b>
<a href="#validIDModal" data-toggle="modal" data-target="#validIDModal">
<i class="material-icons">add_circle</i>
</a>
<div id="validIDList" class="container-fluid">
</div>
</div>
</div>
</div>
<div >
<div >
<b>Family Details</b>
</div>
<div>
<div>
Marital Status:
<select id="maritalStatusList" name="empMaritalStatus" onchange="myFunction()">
<option value="Single">Single
<option value="Married">Married
<option value="Divorced">Separated
<option value="Widowed">Widowed
</select>
<div id="marriedInputs">
</div>
Emergency Contact Information:<br/>
<label for="sameCheckbox">
<input id="sameCheckbox" type="checkbox" name="emergencySameSpouse" value="true" onchange="sameChecked()" disabled>
Emergency Contact Same as Spouse (if present)
</label><br/>
<input id="relationLname" type="text" name="emergencyLname" placeholder="Last Name" required><br/>
<input id="relationFname" type="text" name="emergencyFname" placeholder="First Name" required><br/>
<input id="relationMname" type="text" name="emergencyMname" placeholder="Middle Name" required><br/>
<input id="relationNum" type="text" name="emergencyPhone" placeholder="Phone/Contact Number" required><br/>
<input id="relation" type="text" name="relationship" placeholder="Relationship To Emergency Contact" required>
</div>
</div>
</div>
<div >
<div >
<b>Company Details</b>
</div>
<div >
<div>
<input type="text" name="empQualification" placeholder="Qualification" required><br>
<input type="text" name="empCertification" placeholder="Certification" required><br>
<input type="text" name="empLastEmp" placeholder="Last Employer" required><br>
<input type="text" name="empOverall" placeholder="Overall Years of Workin Exp" onkeypress="return isNumberKey(event)" required><br>
<label>
Hired Date:
<input type="date" name="hiredDate" required>
</label><br>
<input type="text" name="empCompanyID" placeholder="Employee No./ID" required><br>
<input type="text" name="empTitle" placeholder="Title" required><br>
<input type="text" name="empDepartment" placeholder="Department" required><br>
<input type="text" name="empSalary" placeholder="Salary" onkeypress="return isNumberKey(event)" required><br/>
<select name="salaryType">
<option value="">Salary Type</option>
<option value="dailyType">Daily</option>
<option value="monthlyType">Monthly</option>
</select><br>
<input type="text" name="empBenefits" placeholder="Benefits" required><br>
<input type="text" name="empTaxAmount" placeholder="Tax Amount" onkeypress="return isNumberKey(event)" required><br>
<input type="text" name="empSSSAmount" placeholder="SSS Amount" onkeypress="return isNumberKey(event)" required><br>
<input type="text" name="empPhilhealthAmount" placeholder="PhilHealth Amount" onkeypress="return isNumberKey(event)" required><br>
<select name="empStatus" required>
<option value="">Employment Status</option>
<option value="Full Time">Full Time</option>
<option value="Part Time">Part Time</option>
<option value="Casual">Casual</option>
<option value="Fixed Term">Fixed Term</option>
<option value="Shiftworker">Shiftworker</option>
<option value="Probation">Probation</option>
<option value="Others">Others</option>
</select><br>
</div>
</div>
</div>
<div >
<div >
<b>Education Details</b>
</div>
<div>
<div >
<input type="text" name="empHighestEdu" placeholder="Highest Level of Education" required><br>
<input type="text" name="empInstitution" placeholder="Institution" required><br>
<input type="text" name="empCourse" placeholder="Major/Course" required><br>
<input type="text" name="empAwards" placeholder="Awards" required><br>
<input type="text" name="empGradYear" placeholder="Year of Graduation" onkeypress="return isNumberKey(event)" required><br>
</div>
</div>
</div>
<div align="center">
<button type="submit" name="newEmpSubmit" class="flat-butt">ADD</button>
</form>
<a href="add_employee.php">
<button type="button" class="flat-butt">RESET</button>
</a>
<a href="employee.php">
<button type="button" class="flat-butt" >CANCEL</button>
</a>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap JavaScript plugins) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery/1.7.2/jquery.min.js"><\/script>')</script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
function addValidID() {
var idArray = [];
$.each($("input[type='checkbox']:checked"), function(){
idArray.push($(this).val());
});
var container = document.getElementById('validIDList');
container.innerHTML = "";
for(var x = 0; x < idArray.length; x++) {
var chosenFinal = createChosenFinalInput({
"value": idArray[x],
});
var chosenInfo = createChosenInfoInput({
"placeholder": idArray[x] + " Info",
}, idArray[x]);
container.appendChild(chosenFinal);
container.appendChild(chosenInfo);
}
}
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function myFunction() {
var marriedInputs = document.getElementById("marriedInputs");
var status = document.getElementById("maritalStatusList").value;
var sameCheckbox = document.getElementById("sameCheckbox");
if (status == "Married") {
marriedInputs.appendChild(getMarriageDetailsForm());
sameCheckbox.disabled = false;
} else {
marriedInputs.innerHTML = '';
sameCheckbox.disabled = true;
sameCheckbox.checked = false;
}
}
function getMarriageDetailsForm() {
var form = document.createElement('div');
form.setAttribute('id', 'marriedStatusForm');
var spouseLabel = document.createElement("LABEL");
spouseLabel.setAttribute("id", "spouseLabelID");
spouseLabel.for = document.getElementById("spouseLname");
var spouseLabelText = document.createTextNode("SPOUSE: ");
spouseLabel.appendChild(spouseLabelText);
var spouseLnameInput = createInput({
"id": "spouseLname",
"type": "text",
"name": "spouseLastName",
"placeholder": "Last Name",
"onkeyup": "sameChecked()",
})
var spouseFnameInput = createInput({
"id": "spouseFname",
"type": "text",
"name": "spouseFirstName",
"placeholder": "First Name",
"onkeyup": "sameChecked()",
})
var spouseMnameInput = createInput({
"id": "spouseMname",
"type": "text",
"name": "spouseMiddleName",
"placeholder": "Middle Name",
"onkeyup": "sameChecked()",
});
var childrenNumInput = createInput({
"id": "childrenNum",
"type": "text",
"name": "numOfChildren",
"placeholder": "Number of Children",
"onkeypress": "return isNumberKey(event)",
})
var contactNumInput = createInput({
"id": "contactNum",
"type": "text",
"name": "spouseContactNo",
"placeholder": "Contact Number",
})
var addressInput = createInput({
"id": "address",
"type": "text",
"name": "spouseAddress",
"placeholder": "Address",
})
form.appendChild(spouseLabel);
form.appendChild(document.createElement("BR"));
form.appendChild(spouseLnameInput);
form.appendChild(document.createElement("BR"));
form.appendChild(spouseFnameInput);
form.appendChild(document.createElement("BR"));
form.appendChild(spouseMnameInput);
form.appendChild(document.createElement("BR"));
form.appendChild(childrenNumInput);
form.appendChild(document.createElement("BR"));
form.appendChild(contactNumInput);
form.appendChild(document.createElement("BR"));
form.appendChild(addressInput);
form.appendChild(document.createElement("BR"));
return form;
}
function createInput(options) {
var input = document.createElement('INPUT');
input.required = true;
for (var k in options) {
input.setAttribute(k, options[k]);
}
return input;
}
function createChosenFinalInput(options) {
var input = document.createElement('INPUT');
input.setAttribute('name', 'chosenIDFinal[]');
for (var k in options) {
input.setAttribute(k, options[k]);
}
input.hidden = true;
return input;
}
function createChosenInfoInput(options, inputLabel) {
var input = document.createElement('INPUT');
var label = document.createElement('LABEL');
input.setAttribute('name', 'chosenIDInfo[]');
input.setAttribute('type', 'text');
for (var k in options) {
input.setAttribute(k, options[k]);
}
input.required = true;
label.appendChild(document.createTextNode(inputLabel + ":" + "\u00A0"));
label.appendChild(input);
return label;
}
function sameChecked() {
if (sameCheckbox.checked == true) {
document.getElementById("relationLname").value = document.getElementById("spouseLname").value;
document.getElementById("relationFname").value = document.getElementById("spouseFname").value;
document.getElementById("relationMname").value = document.getElementById("spouseMname").value;
document.getElementById("relationNum").value = document.getElementById("contactNum").value;
document.getElementById("relationLname").readonly = true;
document.getElementById("relationFname").readonly = true;
document.getElementById("relationMname").readonly = true;
document.getElementById("relationNum").readonly = true;
document.getElementById("relation").value = "Spouse";
document.getElementById("relation").readonly = true;
} else {
document.getElementById("relationLname").value = "";
document.getElementById("relationFname").value = "";
document.getElementById("relationMname").value = "";
document.getElementById("relationNum").value = "";
document.getElementById("relation").value = "";
document.getElementById("relationLname").readonly = false;
document.getElementById("relationFname").readonly = false;
document.getElementById("relationMname").readonly = false;
document.getElementById("relationNum").readonly = false;
document.getElementById("relation").readonly = false;
}
}
</script>
</body>
</html>
This is from phpfiddle, I can't seem to link it directly, so I posted it directly here.
The initial code has the error, when you add 1 or more IDs, the chosenIDFinal will not be received by the POST.
To solve this, adjust the starting form tag just above the input for the Last Name. This is how I initially conclude that the input type="file" is the culprit. but when I just isolate the culprit and the JS-inputs, it works. So I'm confused as to what is the real culprit

My contact form gives me an internal server error (500) after testing / PHPMailer [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I've done my own mail.php before, but I've been learning about PHPMailer and wanted to implement it on my form for my new site in development. Every time I test it by entering information and hitting send, it gives me an Internal Server Error, and not really explaining why, but it may have something to do with my header perhaps.
my site/page for reference
My code:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="php/mail.php" method="POST">
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="Full Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email Address" required>
<small class="text-muted">I will never share your email with anyone. Pinky swear.</small>
</div>
<div class="form-group">
<input type="phone" class="form-control" id="phone" placeholder="Phone Number" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="company" placeholder="Company (optional)">
</div>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="radio" id="optionsRadios1" value="Project" checked>Project
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="radio" id="optionsRadios2" value="Collab">Collaboration
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="radio" id="optionsRadios3" value="Other">Other
</label>
</div>
</div>
<div class="form-group">
<textarea class="form-control" id="message" rows="4" placeholder="What do you need?" required></textarea>
</div>
<button class="btn btn-primary" style="float: right;" type="submit">Send Away!</button>
</form>
Here's my php
<?php
//gather all form fields
$name = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$phone = mysqli_real_escape_string($db, $_POST['phone']);
$company = mysqli_real_escape_string($db, $_POST['company']);
$radio = mysqli_real_escape_string($db, $_POST['radio']);
$message = mysqli_real_escape_string($db, $_POST['message']);
if($name == "" || $email == "" || $phone == "" || $company == "" || $radio == "" || $message == "" ){
//this could load a modal or some type of error pop up
echo '<div class="alert alert-danger">The form submission is missing values.</div>';
exit();
}
else {
//include autoload
require 'php/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isMail(); // Set mailer to use SMTP
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('renegade13design#gmail.com', 'Joe User'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = '
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="" type="text/css" media="screen, projection" />
<style>
h1 { font-size: 14px; }
body {font-family: helvetica neue, arial;}
</style>
</head>
<body>
<table style="width: 600px; padding: 12px;" align="center">
<tr>
<td><img src="img/form.jpg"></td>
</tr>
<tr>
<td><strong>Full Name:</strong> '.$name.'</td>
</tr>
<tr>
<td><strong>Email Address:</strong> '.$email.'</td>
</tr>
<tr>
<td><strong>Phone Number:</strong> '.$phone.'</td>
</tr>
<tr>
<td><strong>Company:</strong> '.$company.'</td>
</tr>
<tr>
<td><strong>What do you want?:</strong> '.$radio.'</td>
</tr>
<tr>
<td><strong>What do you need?:</strong> '.$message.'</td>
</tr>
</table>
</body>
</html>
';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
header( 'http://www.scratchmediaohio.com/twentysixteen' );
}
}
?>
you dont have the "name" attribute for some of your inputs - therefore they will not be a part of the $_POST array, and therefore not be present for your mail script.
<input type="text" class="form-control" id="name" placeholder="Full Name" required>
should be
<input type="text" class="form-control" name="name" id="name" placeholder="Full Name" required>
for your inputs:name, email,phone and company - the only one that does have them is the radio selection. I would also suggest more validation for your inputs than you currently have.

improved formatting

I have an HTML form that is a div in a bigger page:
<form action="send_form_email.php" method="post">
<h4>E-mail</h4>
<div class="border-stripes">
<input type="email" class="textfield" name="email" placeholder="Your e-mail address" />
</div>
<h4>Message</h4>
<div class="border-stripes">
<textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea>
</div>
<br />
<br />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
and I have this php code
if ($_POST['submit']) {
if ($email == false) {
// ***Insert <p>invalid email address</p> above <h4>email</h4>***
} else if (strlen(trim($_REQUEST['message'])) == 0) {
// ***Insert <p>Send a Message</p> above <h4>email</h4>***
} else if (mail($to, $subject, $message, $email)) {
// ***Insert <p>Successfully sent</p> above <h4>email</h4>***
}
}
My problem is that I don't know how to add that extra paragraph according to the if statement, and then I want the page to automatically scroll down to the form displaying the error.
For instance, if the email address was invalid, I want the page to be redirected to the form div and display above "Email" that the email address is invalid
Put your message into a variable for each if statement like this:
if ($_POST['submit']) {
if ($email == false) {
$msg = "<p>invalid email address</p>";
} else if (strlen(trim($_REQUEST['message'])) == 0) {
$msg = "<p>Send a Message</p>";
} else if (mail($to, $subject, $message, $email)) {
$msg = "<p>Successfully sent</p>";
}else{
$msg ="";
}
}else{
$msg = "";
}
And then echo your message above the email field:
<form action="send_form_email.php" method="post">
<?php echo $msg; ?>
<h4>E-mail</h4>
<div class="border-stripes">
<input type="email" class="textfield" name="email" placeholder="Your e-mail address" />
</div>
<h4>Message</h4>
<div class="border-stripes">
<textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea>
</div>
<br />
<br />
<input id="submit" name="submit" type="submit" value="Submit">
What I understand from the problem you stated here is that -- you want to display error or success message if the post is submitted successfully or not.
For that you you can write both the code in same file send_form_email.php like as below.
<?php
if (isset($_POST)) {
if ($_POST['email'] == false) {
$msg = "<p>invalid email address</p> above <h4>email</h4>";
} else if (strlen(trim($_POST['message'])) == 0) {
$msg = "Insert <p>Send a Message</p> above <h4>email</h4>";
} else if (mail($to, $subject, $message, $email)) {
$msg = "Insert <p>Successfully sent</p> above <h4>email</h4>";
}
}
?>
<html>
<head>
<title> My First Form </title>
</head>
<body>
<form action="send_form_email.php" method="post">
<h4>E-mail</h4>
<div class="border-stripes">
<input type="email" class="textfield" name="email" placeholder="Your e-mail address" />
</div>
<h4>Message</h4>
<div class="border-stripes">
<textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea>
</div>
<br />
<br />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
<div class="msg-box">
<?php echo $msg ? $msg : ''; ?>
</div>
</body>
</html>

Categories

Resources