So here is my problem. if you follow the pictures. simple form. click on name. name moves up underline pulls across. you fill out name then go to next. It gives a nice background with checkmark. validation works great, but problem is with picture 5. after form is checked with php it comes back as errors which is great, but the blue background is gone and the text is behind the name placeholder. Does anyone have a solution to why this is happening?
resting
when clicked
when filled
when completed
error and name is hidden until clicked
clicked
The problem I am having is if the fill something out and forget to fill out a required field. The input they filled out is still there but hidden. You can see it if you click the field, but I would like it to stay like when you first fill it out. I know this may sound confusing thats why i am putting the code here. I hope someone out there could teach me some knowledge!
form.
<?php include('validate.php');?>
<?php include('header.php') ?>
<form id="contact_form" class="contact_form" action="contact.php"
id="contact_form" method="post">
<h2>Have a Question?</h2>
<div class="textinput <?php echo $nameErr ?>">
<?php
if(!empty($nameErr))
{
?>
<div class="requiredline">
</div>
<?php
}
?>
<div class="textinput ">
<input name="Name" type="text" id="Name"
placeholder="First & Last"
value="<?php echo (isset($Name) ? $Name : ""); ?>" />
<label for="Name">Name</label><div class="labelunderline"></div>
</div><span class='text_error'><?php echo $nameErr;?></span>
<div class="textinput <?php echo $nameErr ?>">
<?php
if(!empty($nameErr))
{
?>
<div class="requiredline">
</div>
<?php
}
?>
<div class="textinput">
<input name="Email" type="text" id="Email"
placeholder="Email#mail.com" value="<?php echo (isset($Email) ? $Email : ""); ?>" />
<label for="Email">Email</label>
<div class="labelunderline"></div><!--END LABEL UNDERLINE-->
</div><span class='text_error'><?php echo $emailErr;?></span>
<div class="textinput ">
<input type="text" id="Message" placeholder="Write what you feel" />
<label for="Message">Message</label><div class="labelunderline"></div>
</div>
<div class="input-wrap">
<button id="submit" name="submit" type="submit" value="SUBMIT"
class="col-xs-12 col-sm-8 col-md-6">Submit</button>
</div>
</form><!--END FORM-->
<?php include('footer.php') ?>
footer that holds the javascript for when option is filled.
<script>
$(".textinput input").change(function() {
if ($(this).val() != "") {
$(this).addClass('filled');
} else {
$(this).removeClass('filled');
}
})
</script>
</body>
</html>
css
body {
margin: 0;
padding: 0;
overflow-x: hidden;
}
/*============CONTACT PAGE=====================*/
#contact_header_text {
width: 100%;
height: 55vh;
padding-top: 135px;
font-family: Raleway-reg;
font-size: 2.5em;
color: white;
background-image:
linear-gradient(0deg, rgba(0, 79, 88, 0.5),
100%, rgba(0, 0, 0, 0.0)), url("../images/IMG_1464.jpg");
background-attachment: fixed;
background-repeat: no-repeat;
background-position: top center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-color: #dbdbdb;
}
#contact_section {
text-align: center;
font-size: 1.5em;
color: #333;
font-family: Raleway-reg;
background-color: #fff;
}
#contact_form {
max-width: 1200px;
margin: 0px auto 0px auto;
padding-top: 35px;
padding: 20px;
}
::-webkit-input-placeholder {
text-align: right;
font-family: Raleway-reg;
font-style: italic;
font-weight: bold;
color: #096771;
font-size: 15px;
}
::-moz-placeholder {
text-align: right;
font-family: Raleway-reg;
font-style: italic;
font-weight: bold;
color: #096771;
font-size: 15px;
}
button {
background: #3eacb8;
border: none;
border-radius: 2px;
color: #fff;
padding: 25px;
font-size: 14px;
font-weight: bold;
text-transform: uppercase;
text-align: center;
vertical-align: middle;
font-family: Raleway-med;
margin-bottom: 30px;
letter-spacing: 3px;
}
button:hover {
background-color: #096771;
transition: 0.5s all;
text-decoration: none;
letter-spacing: 6px;
}
label {
top: 10px;
position:absolute;
left: 35px;
transition: all 0.8s ease-in-out;
}
.textinput {
height: 3em;
margin: 1em 0;
position: relative;
width: 100%;
}
.textinput input,
.textinput label {
cursor: pointer;
font-size: 1.25em;
font-family: Raleway-reg;
text-align: left;
padding: 0.6em 1% 0.15em 1%;
/*
position: absolute;
*/
transition: all 0.15s ease;
width: 100%;
}
.labelunderline {
height: 1px;
width: 100%;
background-color: #3eacb8;
position: absolute;
bottom: 3px;
left: 0;
}
.textinput input {
text-decoration: none;
position: relative;
display: inline-block;
border-bottom: 3px solid transparent;
border-left: none;
border-top: none;
border-right: none;
width: 0%;
float: left;
transition: 0.5s ease;
white-space: nowrap;
}
.textinput input:focus {
border-bottom: 3px solid #096771;
width: 100%;
}
.textinput input.filled {
width: 100%;
}
.textinput label {
color: #3eacb8;
padding: 0.6em 0;
margin-left: -1em;
}
.textinput input.filled ~ label,
.textinput input:focus ~ label {
font-size: 0.6em;
font-weight: 600;
margin-top: -15px;
position: absolute;
}
.textinput input.filled ~ label {
color: #096771;
}
.textinput input[type="text"].filled,
.textinput input[type="email"].filled:valid {
background: #3eacb8;
color: white;
opacity: 0.4;
}
/*=================CHECKMARK========================*/
.textinput input[type="text"].filled ~label:after,
.textinput input[type="email"].filled:valid ~label:after {
color: #096771;
content: "\f058";
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: 3em;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
position: absolute;
top: 15px;
right: 35px;
transform: translate(0, 0);
}
.error {
/*
text-align: left;
margin-top: 5px;
*/
color: #FF0000;
font-family: pathwaygothic;
/*
display: block;
background-image:url(../images/x.png);
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
*/
}
.text_error {
text-align: left;
margin-top: -15px;
color: #FF0000;
display: block;
font-family: pathwaygothic;
background-image:url(../images/x.png);
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
}
div.error {
text-align: left;
font-size: 19px;
margin-top: 5px;
background-image:url(../images/x.png);
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
margin-left: 25px;
}
.requiredline {
height: 4px;
width: 100%;
position: absolute;
bottom: 0px;
left: 0;
background-color: red;
}
and lastly the validate form
<?php
session_start();
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = $describeErr = $humanErr = $subjectmatterErr = "";
$Name = $Email = $Phone = $Describe = $Human =
$Subjectmatter = "";
$hasError = false;
$sent = false;
if(isset($_POST['submit'])) {
$Name = trim(htmlspecialchars($_POST['Name'], ENT_QUOTES));
$Email = trim($_POST['Email']);
$Describe = trim(htmlspecialchars($_POST['Describe'], ENT_QUOTES));
$Phone = trim($_POST['Phone']);
$Company = trim($_POST['Company']);
$Website = trim($_POST['Website']);
$Subjectmatter = trim($_POST['Subjectmatter']);
$Human = trim($_POST['Human']);
$Number = 8;
$fieldsArray = array(
'Name' => $Name,
'Email' => $Email,
'Describe' => $Describe,
'Phone' => $Phone,
'subjectmatter' => $Subjectmatter,
'Human' => $Human
);
$errorArray = array();
foreach($fieldsArray as $key => $val) {
switch ($key) {
case 'Name':
if(empty($val)) {
$hasError = true;
$nameErr = "Please enter your name.";
}
case 'Name':
if (!preg_match("/^[a-zA-Z ]*$/", ($val))) {
$hasError = true;
$nameErr = "The value must be alphanumeric.";
}
break;
case 'Phone':
if (!preg_match("/^[0-9]+$/", ($val))) {
$hasError = true;
$phoneErr = "Only numbers and white space allowed.";
}
case 'Phone':
if(empty($val)) {
$hasError = true;
$phoneErr = "Phone is required.";
}
break;
case 'Subjectmatter':
if(empty($val)) {
$hasError = true;
$subjectmatterErr = "Subject is required.";
}
break;
case 'Email':
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$hasError = true;
$emailErr = "Email is required.";
} else {
$Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
}
break;
case 'Describe' :
if (strlen($val) < 25) {
$hasError = true;
$describeErr = "Please enter at least 25 characters.
This way I know more specifically what you need!";
}
case 'Describe' :
if(empty($val)) {
$hasError = true;
$describeErr = "Message is required.
This way I know what you need!";
}
break;
case 'Human':
if (!preg_match("/[^\d]?8[^\d]?/", ($val))) {
$hasError = true;
$humanErr = "Not the right answer";
}
case 'Human':
if (!preg_match("/^[0-9]+$/", ($val))) {
$hasError = true;
$humanErr = "Must be a number";
}
case 'Human':
if(empty($val)) {
$hasError = true;
$humanErr = "Are you human?";
}
break;
}
}
//Validation Success!
//Do form processing like email, database etc here
if($hasError !== true) {
$priority = $_POST['priority'];
$type = $_POST['type'];
$message = $_POST['message'];
$formcontent=" From: $Name \n Company: $Company \n
Email: $Email \n Phone: $Phone \n
Website: $Website \n Subject: $Subjectmatter
\n Describe: $Describe \n\n";
$recipient = "email#email.com";
$subject = "Contact Form";
$mailheader = "From: $Email \r\n";
mail($recipient, $subject, $formcontent,
$mailheader /*$message, $headers*/);
header("Refresh:0; url=thanks.php");
exit();
}
}
?><!--END PHP-->
I know someone can figure out where i screwed up!
The problem is that the blue background comes from the change event handler, which adds and removes the class 'filled' to the input, but when you reload the page nobody calls it.
To let things easy I suggest that you refactor your javascript and call it on
$(document).ready.
Try this
$(document).ready(function(){
function checkInput(elem){
if ($(elem).val() != "") {
$(elem).addClass('filled');
} else {
$(elem).removeClass('filled');
}
}
$(".textinput input").change(function() {
checkInput(this);
});
$(".textinput input").each(function(){
checkInput(this);
});
}
Otherwise you can do it in the php side. Then on every input you've to check whether the field has a values with issetand add the class to the input.
Fiddle
Related
First of all, I'm new to website creation and especially to php.
I have created a contact form for my website with a validation and a message that is displayed if everything is filled in correctly (see the snippet below). I know that the validation has to be done on both the client and server side, but I know that I am dealing with something else.
I have created a php file that works: I get the email when the user clicks submit.
I am faced with two things.
How do I keep the javascript validation and the message on the front end?
How do I configure the php to stay on the page, or better yet, run in the back and only submit the form to my email?
<?php
if(isset($_POST['submit'])){
$mailto = "contact#statsmap.ch"; //Send the email to this adress
//All the inputs informations
$mailfrom = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
//$message = "NAME: " .$name. "\r\n\n". "Wrote the following Message:" ."\r\n". $_POST['message'];
$message = $_POST['message'];
$headers = "From: ". $mailfrom;
$sendMail = mail($mailto, $subject, $message, $headers); // Send mail to website owner
}
?>
const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');
const isValidEmail = (email) => {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
};
let isValid = true;
function checkInputs(){
//get the values from the inputs or textarea
const nameValue = nameContact.value.trim();
const emailValue = emailContact.value.trim();
const messageValue = messageContact.value.trim();
if (nameValue === ''){
//show error
//add error class
setErrorFor(nameContact, 'Name cannot be blank');
} else{
//add success class
setSuccesFor(nameContact);
}
if (emailValue === ''){
//show error
//add error class
setErrorFor(emailContact, 'Email cannot be blank');
} else if(!isValidEmail(emailValue)){
setErrorFor(emailContact, 'Please add a valid email adress');
} else{
setSuccesFor(emailContact);
}
if (messageValue === ''){
//show error
//add error class
setErrorFor(messageContact, 'Message cannot be blank');
} else if (messageValue.length < 20){
setErrorFor(messageContact, 'Message need to be at least 20 characters');
}
else{
//add success class
setSuccesFor(messageContact);
}
}
function setErrorFor(input, message){
isValid=false;
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//add error message inside the span
errorContactMessage.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input){
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//remove message inside the span
errorContactMessage.innerText='';
//add success class
formControl.className = 'form-control success';
}
let nameThk = "";
nameContact.addEventListener('input', (e) =>{
nameThk = e.target.value;
});
form.addEventListener('submit', () =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
}
});
.containerContact {
background-color: #F8F8F8;
width: 100%;
max-width: 100%;
padding: 0.5rem;
display: block;
}
.containerContact h2 {
margin-bottom: 0.5rem;
}
.form-control {
margin-bottom: 0.25rem;
position: relative;
}
.form-control input {
display: block;
width: 100%;
height: 2rem;
padding-left: 0.5rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-size: 0.8125rem;
color: #000000;
}
.form-control input::-webkit-input-placeholder {
color: #000000;
}
.form-control input:-ms-input-placeholder {
color: #000000;
}
.form-control input::-ms-input-placeholder {
color: #000000;
}
.form-control input::placeholder {
color: #000000;
}
.form-control textarea {
width: 100%;
height: 10rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-family: Arial, Helvetica, sans-serif;
padding: 0.5rem;
font-size: 0.8125rem;
color: #000000;
resize: none;
}
.form-control textarea::-webkit-input-placeholder {
color: #000000;
}
.form-control textarea:-ms-input-placeholder {
color: #000000;
}
.form-control textarea::-ms-input-placeholder {
color: #000000;
}
.form-control textarea::placeholder {
color: #000000;
}
.form-control i {
position: absolute;
top: 0.5rem;
right: 0.5rem;
visibility: hidden;
}
.form-control #textareaChecks {
position: absolute;
top: 8.5rem;
right: 0.5rem;
}
.form-control.success input {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.success textarea {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
#Error {
font-weight: 500;
font-size: 0.75rem;
font-style: italic;
color: red;
margin: 0;
padding: 0;
}
#ContactSubmit {
width: 100%;
height: 2rem;
background: #1e1e1e;
outline: none;
border: 0.025rem solid #000000;
color: #FFFFFF;
}
.containerThank {
height: 300px;
display: -ms-grid;
display: grid;
}
.containerThank h3 {
margin: 0;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
font-size: 18px;
font-weight: bold;
}
.containerThank p {
-ms-flex-item-align: start;
align-self: flex-start;
text-align: center;
font-size: 13px;
padding-top: 0.5rem;
}
.hide {
display: none;
}
<form action="/php/contactMail.php" method="POST" class="formContact" id="formContact" novalidate>
<div class="form-control">
<input type="text" name="name" id="name" placeholder="First and Last name">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="email" name="email" id="email" placeholder="Please enter your email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="text" name="subject" id="subject" placeholder="Subject">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<textarea id="message" name="message" type="text" placeholder="Message"></textarea>
<i id="textareaChecks" class="fas fa-check-circle"></i>
<i id="textareaChecks" class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<button id="ContactSubmit" name="submit">Submit</button>
</form>
<div class="Thankyou hide">
<div class="containerThank">
<h3 id="merci"></h3>
<p>Our team is going to get back to you as soon as possible</p>
</div>
</div>
</div>
</div>
</section>
</div>
Looks like you checked the variable isValid for it to be true, but you didn't provide an alternative if isValid is false.
Basically, I edited this:
form.addEventListener('submit', (e) =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
} else {
e.preventDefault()
}
As you can see, if isValid is false, the script prevents the form from submitting.
Working snippet:
const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');
const isValidEmail = (email) => {
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
};
let isValid = true;
function checkInputs(){
//get the values from the inputs or textarea
const nameValue = nameContact.value.trim();
const emailValue = emailContact.value.trim();
const messageValue = messageContact.value.trim();
if (nameValue === ''){
//show error
//add error class
setErrorFor(nameContact, 'Name cannot be blank');
} else{
//add success class
setSuccesFor(nameContact);
}
if (emailValue === ''){
//show error
//add error class
setErrorFor(emailContact, 'Email cannot be blank');
} else if(!isValidEmail(emailValue)){
setErrorFor(emailContact, 'Please add a valid email adress');
} else{
setSuccesFor(emailContact);
}
if (messageValue === ''){
//show error
//add error class
setErrorFor(messageContact, 'Message cannot be blank');
} else if (messageValue.length < 20){
setErrorFor(messageContact, 'Message need to be at least 20 characters');
}
else{
//add success class
setSuccesFor(messageContact);
}
}
function setErrorFor(input, message){
isValid=false;
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//add error message inside the span
errorContactMessage.innerText = message;
//add error class
formControl.className = 'form-control error';
}
function setSuccesFor(input){
const formControl = input.parentElement;
const errorContactMessage = formControl.querySelector('#Error');
//remove message inside the span
errorContactMessage.innerText='';
//add success class
formControl.className = 'form-control success';
}
let nameThk = "";
nameContact.addEventListener('input', (e) =>{
nameThk = e.target.value;
});
form.addEventListener('submit', (e) =>{
checkInputs();
if(isValid){
form.remove();
headerContact.classList.add('hide');
thankYou.classList.remove('hide');
document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
} else {
e.preventDefault()
}
});
.containerContact {
background-color: #F8F8F8;
width: 100%;
max-width: 100%;
padding: 0.5rem;
display: block;
}
.containerContact h2 {
margin-bottom: 0.5rem;
}
.form-control {
margin-bottom: 0.25rem;
position: relative;
}
.form-control input {
display: block;
width: 100%;
height: 2rem;
padding-left: 0.5rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-size: 0.8125rem;
color: #000000;
}
.form-control input::-webkit-input-placeholder {
color: #000000;
}
.form-control input:-ms-input-placeholder {
color: #000000;
}
.form-control input::-ms-input-placeholder {
color: #000000;
}
.form-control input::placeholder {
color: #000000;
}
.form-control textarea {
width: 100%;
height: 10rem;
background: transparent;
border: 0.025rem solid #000000;
outline: none;
font-family: Arial, Helvetica, sans-serif;
padding: 0.5rem;
font-size: 0.8125rem;
color: #000000;
resize: none;
}
.form-control textarea::-webkit-input-placeholder {
color: #000000;
}
.form-control textarea:-ms-input-placeholder {
color: #000000;
}
.form-control textarea::-ms-input-placeholder {
color: #000000;
}
.form-control textarea::placeholder {
color: #000000;
}
.form-control i {
position: absolute;
top: 0.5rem;
right: 0.5rem;
visibility: hidden;
}
.form-control #textareaChecks {
position: absolute;
top: 8.5rem;
right: 0.5rem;
}
.form-control.success input {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error input {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
.form-control.success textarea {
border-color: green;
}
.form-control.success i.fa-check-circle {
visibility: visible;
color: green;
}
.form-control.error textarea {
border-color: red;
}
.form-control.error i.fa-exclamation-circle {
visibility: visible;
color: red;
}
#Error {
font-weight: 500;
font-size: 0.75rem;
font-style: italic;
color: red;
margin: 0;
padding: 0;
}
#ContactSubmit {
width: 100%;
height: 2rem;
background: #1e1e1e;
outline: none;
border: 0.025rem solid #000000;
color: #FFFFFF;
}
.containerThank {
height: 300px;
display: -ms-grid;
display: grid;
}
.containerThank h3 {
margin: 0;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
font-size: 18px;
font-weight: bold;
}
.containerThank p {
-ms-flex-item-align: start;
align-self: flex-start;
text-align: center;
font-size: 13px;
padding-top: 0.5rem;
}
.hide {
display: none;
}
<form action="/php/contactMail.php" method="POST" class="formContact" id="formContact" novalidate>
<div class="form-control">
<input type="text" name="name" id="name" placeholder="First and Last name">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="email" name="email" id="email" placeholder="Please enter your email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<input type="text" name="subject" id="subject" placeholder="Subject">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<div class="form-control">
<textarea id="message" name="message" type="text" placeholder="Message"></textarea>
<i id="textareaChecks" class="fas fa-check-circle"></i>
<i id="textareaChecks" class="fas fa-exclamation-circle"></i>
<span id="Error"></span>
</div>
<button id="ContactSubmit" name="submit">Submit</button>
</form>
<div class="Thankyou hide">
<div class="containerThank">
<h3 id="merci"></h3>
<p>Our team is going to get back to you as soon as possible</p>
</div>
</div>
</div>
</div>
</section>
</div>
I'm trying to make a login form that check if my data are correct.
For example, if I insert a different value than "new_user" in the username field, then it should display a red error message under the submit button saying "please insert a valid user", and the border of the input field should be red as well.
If the username field is empty it has to do the same thing, just that the error message now has to be "please insert a username" and the same thing has to apply for the password field.
If the values for both username and password are matching has to display the message "Successfully Login"
I will attach an image just as an example, and I have added my code below. Please feel free to tell me what am I doing wrong.
var form = document.getElementById("form");
var user = document.getElementById("username");
var pass = document.getElementById("password");
var botton = document.getElementById("btn")
var validUser = "new_user";
var validPassword = 123456789;
form.addEventListener("submit", function(e) {
e.preventDefault();
checkInputs();
})
user.addEventListener("input", function() {
var username = user.value;
if (username) {
if (username === " " || username == null) {
setErrorFor(user, "Please insert a username");
} else if (username !== validUser) {
setErrorFor(user, "Please insert a valid username");
}
} else {
setSuccessFor(user, "Successfully Login")
}
})
function setErrorFor(input, message) {
var formControl = input.parentElement;
var showError = document.querySelector(".text-message");
var displayMessage = document.getElementById("msg");
//add error message & add the class name inside the message element
displayMessage.innerHTML = message
showError.className = "text-message invalid"
//add the error class
formControl.classList = "form-control fail"
}
function setSuccessFor(input, message) {
var formControl = input.parentElement;
var showError = document.querySelector(".text-message");
var displayMessage = document.getElementById("msg");
//add error message & add the class name inside the message element
displayMessage.innerHTML = message
showError.className = "text-message valid"
//add the error class
formControl.classList = "form-control success"
}
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
}
#login-container {
width: 45%;
margin: 0 auto;
border-radius: .5em;
position: relative;
background: linear-gradient(to right, rgb(88, 167, 236), rgb(180, 198, 214), rgb(180, 198, 214));
padding: 3em 2.5em;
box-shadow: 0px 5px 4px #424241;
text-align: justify;
}
.input-field {
margin-bottom: .5em;
}
input[type="text"],
input[type="password"] {
width: 100%;
display: inline-block;
outline: none;
font-size: 18px;
padding: .5em 1.5em .5em .5em;
border-radius: .5em;
}
.form-control {
position: relative;
}
.input-field i {
position: absolute;
top: 2.2em;
right: .5em;
opacity: 0;
}
.fa-check {
color: green;
}
.fa-times {
color: red;
}
form label {
font-weight: bold;
display: inline-block;
font-size: 18px;
margin-bottom: .2em;
}
form input[type="submit"] {
background: rgb(112, 112, 112);
border-radius: .5em;
margin: 1em 0 .2em 0;
padding: .5em 0;
display: block;
font-size: 18px;
font-weight: 700;
width: 100%;
position: relative;
text-transform: uppercase;
border: none;
}
form input[type="submit"]:hover {
background-color: #70db70;
color: white;
}
.text-message .msg {
margin: 0;
padding: 0;
font-size: 16px;
}
/*Message classes*/
.form-control.success input {
border: 3px solid green;
}
.form-control.fail input {
border: 3px solid red;
}
.form-control.success i.fa-check {
opacity: 1;
}
.form-control.fail i.fa-times {
opacity: 1;
}
.text-message.valid p {
display: block;
color: green;
}
.text-message.invalid p {
display: block;
color: red;
}
<form id="form">
<div class="input-field">
<div class="form-control">
<label for="username">Username:</label>
<input id="username" class="input" type="text">
<i class="fas fa-check u_check"></i>
<i class="fas fa-times u_decline"></i>
</div>
</div>
<div class="input-field">
<div class="form-control">
<label for="password">Password:</label>
<input id="password" class="input" type="password">
<i class="fas fa-check p_check"></i>
<i class="fas fa-times p_decline"></i>
</div>
</div>
<input type="submit" value="submit" id="btn">
<div class="text-message">
<p id="msg" class="msg"></p>
</div>
I am trying to make a counter for submitting a form in php, if the data from the forms is sent to the server, +1 is written to the counter.txt file, this data is used to form the header in the letter. Everything works, but 5 identical letters come to the mail, the next time it sends 10 and so on. What is the problem? Why is this happening?
When I remove the counter code everything works fine and one letter arrives.
<?php
$email = ($_POST['sel']);
$change = ($_POST['button-set']);
$name = ($_POST['name']);
$question = ($_POST['message']);
$submit = ($_POST['submit']);
if (isset ($submit)) {
$count = file_get_contents ('counter.txt');
$count ++;
file_put_contents ('counter.txt', $count);
}
else {
$count = file_get_contents ('counter.txt');
};
$to = 'support#archsupport.ru';
$subject = 'Application number: ' . $count . 'from the site archsupport.ru';
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question ;
$headers = 'From: zergg52#gmail.com ' . "\r\n";
$subject = preg_replace("/(\r\n)|(\r)|(\n)/", "", $subject);
$subject = preg_replace("/(\t)/", " ", $subject);
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
#mail($to, $subject, $message, $headers);
echo 'message sent!';
var_dump($email,$change,$name,$question,$submit,$count)
?>
Page code:
var form = document.getElementsByTagName('form')[0];
var names = document.getElementById('name');
var validn = document.getElementById('vn');
var iconrequired = document.querySelector('#namereq');
var email = document.getElementById('sellection');
var valids = document.getElementById('vs');
var iconrequireds = document.querySelector('#sellectionreq');
var text = document.getElementById('qestions');
var validt = document.getElementById('vt');
var iconrequiredt = document.querySelector('#textreq');
document.addEventListener('input', function validation() {
var x = document.forms["support"]["sellection"].value;
if (names.validity.valid) {
validn.className = "valid";
iconrequired.className = "iconrequired hide";
};
if (email.validity.valid && x != "") {
valids.className = "valid";
iconrequireds.className = "iconrequired hide";
};
if (text.validity.valid) {
validt.className = "valid";
iconrequiredt.className = "iconrequired hide";
};
if (!names.validity.valid) {
validn.className = "invalid";
iconrequired.className = "iconrequired hide";
};
if (!email.validity.valid) {
valids.className = "invalid";
iconrequireds.className = "iconrequired hide";
};
if (!text.validity.valid) {
validt.className = "invalid";
iconrequiredt.className = "iconrequired hide";
};
if (names.validity.valid && email.validity.valid && text.validity.valid) {
$('#support').submit(function() {
$.post(
'https://www.archsupport.ru/post-email.php',
$("#support").serialize(),
function(msg) {
$('#support').hide('slow');
$('#message').html(msg);
}
);
});
} else {
return false;
}
});
function validateSellection() {
var x = document.forms["support"]["sellection"].value;
if (x === "") {
document.getElementById('sellectionreq').classList.remove("hide");
return false;
} else {
document.getElementById('sellectionreq').classList.add("hide");
return false;
}
};
function validateName() {
var x = document.forms["support"]["name"].value;
if (x === "") {
document.getElementById('namereq').classList.remove("hide");
return false;
} else {
document.getElementById('namereq').classList.add("hide");
return false;
}
};
function validateText() {
var x = document.forms["support"]["qestions"].value;
if (x === "") {
document.getElementById('textreq').classList.remove("hide");
return false;
} else {
document.getElementById('textreq').classList.add("hide");
return false;
}
};
$('#support').submit(function validate() {
if (validateName() && validateSellection() && validateText() === true) {
return false;
} else {
validateSellection();
validateName();
validateText()
return false
}
});
$(".radio").on('click.two', function() {
let input = $("#sellection");
if ($("#radio").prop("checked")) {
input.prop("disabled", false);
input.prop({
"type": "email",
"placeholder": "example#yourmail.ru",
"autocomplete": "email",
"maxlength": "35",
"minlength": "12",
"value": "",
});
document.getElementById("sellection").pattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$";
} else {
input.prop("disabled", false);
$("#sellection").prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
document.getElementById("sellection").pattern = "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}";
}
input.focus();
input.val("");
});
var fab = $('.icons');
fab.on('click.ten', function iconback() {
fab.removeClass('checked');
$(this).addClass('checked');
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/form.css">
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form novalidate action="" method="post" name="support" id="support">
<label class="required"><span id="vs" class="invalid hide"></span><input id="sellection" class="mail sellection" name="sel" vlaue="" placeholder="choose a communication way...." required disabled><span id="error1"></span><div id="sellectionreq" class="iconrequired hide">REQUIRED</div></label>
<div class="button-set">
<label title="Email"><img class="icons" src='/img/icon/social_icon_mail_white.svg'><input class="radio" id="radio" type="radio" name="button-set" value="to mail" style="display:none;"></label>
<label for="radio1" title="WhatsApp"><img class="icons" src='/img/icon/social_icon_whatsapp_white.svg'><input class="radio" id="radio1" type="radio" name="button-set" value="to WhatsApp" style="display:none;"></label>
<label for="radio2" title="Telegram"><img class="icons" src='/img/icon/social_icon_telegram_white.svg'><input class="radio" id="radio2" type="radio" name="button-set" value="to Telegram" style="display:none;"></label>
<label for="radio3" title="Viber"><img class="icons" src='/img/icon/social_icon_viber_white.svg'><input class="radio" id="radio3" type="radio" name="button-set" value="to Viber" style="display:none;"></label>
</div>
<label class="required"><span id="vn" class="invalid hide"></span>
<input id="name" class="mail" type="name" name="name" autocomplete= none placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="message" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="4" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="submit" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
</body>
<script src="/js/form.js"></script>
</html>
without counter:
var_dump($email,$change,$name,$question,$submit) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL
with counter:
var_dump($email,$change,$name,$question,$submit,$count) - string(12)
"+79102054615" string(11) "to WhatsApp" string(4) "ZERG" string(8)
"ANYTHING" NULL string(1) "9"
$count immediately takes on value "9"
site with form: https://www.archsupport.ru/
In regards to the HTML/JavaScript, consider the following code.
$(function() {
var form = $("#support");
function checkFieldValidity(fObj) {
var r = false;
var re = new RegExp(fObj.attr("pattern"));
var v = fObj.val();
if (fObj.is("[required]")) {
if (v.length) {
fObj.next(".iconrequired").hide();
} else {
fObj.next(".iconrequired").show();
}
if (re.test(v)) {
fObj.prev(".icon").removeClass("invalid").addClass("valid");
r = true;
} else {
fObj.prev(".icon").removeClass("valid").addClass("invalid");
}
} else {
r = true;
}
return r;
}
$("input", form).blur(function() {
checkFieldValidity($(this));
});
form.submit(function(e) {
e.preventDefault();
var valid = true;
$("[required]", form).each(function(i, el) {
valid = valid && checkFieldValidity($(el));
});
return valid;
});
$(".button-set label", form).on('click', function() {
$(this).parent().find(".checked").removeClass("checked");
$("img", this).addClass("checked");
var input = $("#sellection");
input.prop("disabled", false);
switch ($(this).data("value")) {
case "email":
input.prop({
type: "email",
placeholder: "example#yourmail.com",
autocomplete: "email",
maxlength: 35,
minlength: 12,
value: "",
}).attr("pattern", "^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$");
break;
// Add Cases for each selection option if needed
default:
input.prop({
"type": "tel",
"placeholder": "+7-910-205-46-15",
"autocomplete": "tel",
"maxlength": "16",
"minlength": "11",
"value": "",
});
input.attr("pattern", "\\+7\\s?[\\(]{0,1}9[0-9]{2}[\\)]{0,1}\\s?\\d{3}[-]{0,1}\\d{2}[-]{0,1}\\d{2}");
break;
}
input.focus();
input.val("");
});
});
#keyframes req {
0% {
transform: translatex(0px);
}
100% {
transform: translatex(5px);
}
}
#keyframes inv {
0% {
opacity: .5;
}
100% {
opacity: 1;
}
}
* {
padding: 0;
margin: 0;
}
:root {
font-family: "HelveticaNeueCyr";
font-weight: 100;
}
form {
font-size: 24px;
position: relative;
width: 100%;
display: inline-flex;
flex-direction: column;
}
textarea {
height: 30vh;
border-radius: 18px;
padding-left: 15px;
padding-top: 10px;
border: 2px solid #d7d7d7;
overflow: hidden;
overflow-y: scroll;
outline: none;
resize: none
}
input,
textarea {
font-family: "HelveticaNeueCyr";
font-weight: 100;
font-size: 18px;
}
::-webkit-input-placeholder {
color: gray;
font-size: 18px;
}
::-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 19+ */
:-moz-placeholder {
color: gray;
font-size: 18px;
}
/* Firefox 18- */
:-ms-input-placeholder {
color: gray;
font-size: 18px;
}
input:not([type="submit"]) {
border-radius: 100px;
padding-left: 15px;
height: 36px;
border: none;
background: #f3f3f3;
}
input:focus {
outline: none;
border: 2px solid #f3f3f3;
box-sizing: border-box;
background: white;
padding-left: 13px;
}
.required {
display: inline-flex;
width: 100%;
flex-direction: column;
margin-bottom: 15px;
position: relative;
}
.iconrequired {
margin: auto;
display: flex;
align-items: center;
justify-content: center;
width: 90px;
height: 14px;
color: white;
border-radius: 100px;
font-size: 10px;
font-weight: 100;
font-family: "HelveticaNeueCyr";
background: #343434;
position: absolute;
right: 15px;
top: 10px;
opacity: 1;
transition: opacity ease-out 1s;
animation: .05s ease-in-out 0s 4 alternate req;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
transition: background-color 5000s ease-in-out 0s;
border: 2px solid #f3f3f3;
box-sizing: border-box;
padding-left: 13px;
}
div.button-set {
display: inline-flex;
}
div.button-set>label {
position: relative;
flex: 0 0 auto;
height: 50px;
width: 50px;
margin-left: 15px;
border-radius: 100px;
outline: none;
border: none;
margin-bottom: 20px;
}
.checked {
background: #f3f3f3;
border-radius: 100px;
}
input[type="submit"] {
font-family: "HelveticaNeueCyr";
height: 36px;
width: 160px;
font-weight: 100;
font-size: 24px;
margin-top: 20px;
margin-left: 10px;
border: none;
border-radius: 100px;
background: #f3f3f3;
padding: 0;
}
::-webkit-scrollbar {
position: absolute;
z-index: 9999;
width: 5px;
}
::-webkit-scrollbar-button {
display: none;
}
::-webkit-scrollbar-track {
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-track-piece {
z-index: 9999;
z-index: 9999;
background-color: transparent;
}
::-webkit-scrollbar-thumb {
z-index: 9999;
background-color: #d7d7d7;
border-radius: 3px;
}
::-webkit-scrollbar-corner {
z-index: 9999;
background-color: #d7d7d7;
}
.invalid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: tomato;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.valid {
width: 12px;
height: 12px;
color: white;
position: absolute;
right: 15px;
top: 12px;
background: #9dc46b;
border-radius: 6px;
animation: 2s ease-in-out 0s infinite alternate inv;
}
.error {
text-align: right;
font-size: 12px;
padding-right: 20px;
padding-top: 10px;
color: gray;
letter-spacing: .05em;
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form novalidate action="" method="post" name="support" id="support">
<span class="icon"></span><input id="sellection" class="mail" name="f[sel]" value="" placeholder="Choose a communication method...." required disabled>
<div class="iconrequired hide">REQUIRED</div>
<div class="button-set">
<label title="Email" data-value="email"><img class="icon" src='/img/icon/social_icon_mail_white.svg'></label>
<label title="WhatsApp" data-value="whatsapp"><img class="icon" src='/img/icon/social_icon_whatsapp_white.svg'></label>
<label title="Telegram" data-value="telegram"><img class="icon" src='/img/icon/social_icon_telegram_white.svg'></label>
<label title="Viber" data-value="viber"><img class="icon" src='/img/icon/social_icon_viber_white.svg'></label>
</div>
<label class="required"><span class="icon"></span>
<input id="name" class="mail" type="name" name="f[name]" autocomplete="none" placeholder="what's your name...." value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="15" minlength="2" required><div id="namereq" class="iconrequired hide">REQUIRED</div></label>
<label class="required"><span id="vt" class="invalid hide"></span><textarea id="qestions" type="text" placeholder="your question...." name="f[message]" value="" pattern="[A-Za-z]+(\s+[A-Za-z]+)?" maxlength="400" minlength="45" required></textarea><div id="textreq" class="iconrequired hide">REQUIRED</div></label>
<input name="f[submit]" type="submit" id="submit" value="SUBMIT" />
</form>
<div id="message"></div>
You want to evaluate if each field that is required has content and matches a specific pattern. I think your approach was too complicated. Additionally, I would stick with all native JavaScript or all jQuery. Don't mix them.
For submit, you will want to test each field and keep a running tally. To do this, you can logically start with a true value and as you test, keep logically evaluating. Example:
var result = true;
result = result && true; // result is true
result = result && false; // result is false
result = result && true; // result is false
If some of the fields validate and if any do not, the result will be false and the form should not submit. If all validate, the result will be true and it's safe to submit the data to PHP. This should also prevent multiple submissions.
Remember that this is Client Side validation and can be bypassed by posting the data manually to the PHP. Most users will not even bother, yet all it takes is one curious or malicious User or Bot to see that they can bypass the form and create their own HTTP Post Payload. So you will want to ensure that your PHP is protected from such actions. Test any data submitted by the User before using it in your PHP Code. For example, you define $name like so:
$name = ($_POST['name']);
If I construct a payload like:
&name=;include "/etc/passwd";
This might get evaluated in the following code:
$message = 'Name: ' . $name . "\r\n" . 'Contacts: ' . $email . "\r\n" . 'Write ' . $change . "\r\n" . 'Question: ' . $question;
Just some things to consider.
I am trying to do both server side and user side input validation, however, when I click my submit button it's not bringing me to my thank you page.
My guessing is that when I use the below function it causes the problem.
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Please let me know what the problem is.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Us</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/contact_form.css">
<script type='text/javascript'>
function validateForm() {
var err = 0;
var fields = document.getElementsByClassName("required");
for (i=0;i<fields.length;i++){
if (fields[i].value === ""){
err += 1;
fields[i].style.backgroundColor = "#ebdded";
}
else{
fields[i].style.backgroundColor = "";
}
}
if(err > 0){
alert("Please Fill the Required Fields");
}
return false;
}
</script>
</head>
<body>
<div class="container">
<div class="form-wrap">
<div class="contact-title">
<div id="circle-container">
<div id="circle-effect">
<div class="circle" id="fifthLayer"></div>
<div class="circle" id="fourthLayer"></div>
<div class="circle" id="thirdLayer"></div>
<div class="circle" id="secondLayer"></div>
<div class="circle" id="firstLayer">Contact Me!</div>
</div>
</div>
</div>
<form name = "_contact_form" class="contact-form" onsubmit="return validateForm()" action="contactform.php" method="POST">
<div class="div-input-form">
<label class="input-label">First Name*: </label>
<input id="fname" class="user-input required" type="text" name="firstName" placeholder="First Name">
</div>
<div class="div-input-form">
<label class="input-label">Last Name*: </label>
<input id = "lname" class="user-input required" type="text" name="lastName" placeholder="Last Name">
</div>
<div class="div-input-form">
<label class="input-label">Email*:</label>
<input id = "email" class="user-input required" type="text" name="email" placeholder="Enter email addess">
</div>
<div class="div-input-form">
<label class="input-label">Phone:</label>
<input class="user-input" type="text" name="phone" placeholder="Enter phone number">
</div>
<div class="div-input-form">
<label class="input-label">Gender:</label>
<input type="radio" class="radio-radio" name = "gender" value="Male"> Male </br>
<input type="radio" class="radio-radio" name = "gender" value="Female"> Female </br>
<input type="radio" class="radio-radio" name = "gender" value="Other"> Other </br> </br>
</div>
<div class="div-input-form">
<label class="input-label">Occupation:</label>
<select name = "dropdown" class="select-occ">
<option value="Student">Student</option>
<option value="Teacher">Teacher</option>
</select>
</div>
<div class="div-input-form">
<label class="input-label">Age:</label>
<input type="radio" class="radio-radio" name = "age" value="18orBelow"> 15 or Below </br>
<input type="radio" class="radio-radio" name = "age" value="19to21"> 16 to 20 </br>
<input type="radio" class="radio-radio" name = "age" value="21orAbove"> 21 or above </br> </br>
</div>
<div class="div-input-form">
</br>
<label class="input-label">How Did You Hear About Us:</label>
<input type="checkbox" class="checkbox" name="hearaboutus"> Internet Search<br>
<input type="checkbox" class="checkbox" name="hearaboutus"> Friends or Family<br>
<input type="checkbox" class="checkbox" name="hearaboutus"> Other<br> </br>
</div>
<div class="div-input-form">
<label class="input-label">Message*:</label>
<textarea id="input_message" class="user-input required" name="message" placeholder="Your Comment..."></textarea>
</div>
<div class="div-submit-button" >
<button id ='submit' name = 'submit-button' class="submit-button">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
contactform.php
<?php
session_start();
if(isset($_POST['submit-button'])){
if(empty($_POST["firstName"])) {
$fnameErr = "First Name is required";
}else {
$firstName = strval(test_input($_POST['firstName']));
}
if (empty($_POST["lastName"])) {
$lnameErr = "Last Name is required";
}else {
$lastName = strval(test_input($_POST['lastName']));
}
if (empty($_POST["email"])) {
$emailErr = "Last Name is required";
}else {
$emailFrom = strval(test_input($_POST['email']));
if (!filter_var($emailFrom, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$mesErr = "Last Name is required";
}else {
$message = strval(test_input($_POST['message']));
}
$phone = strval(test_input($_POST['phone']));
$occupation = strval(test_input($_POST['dropdown']));
$age = strval(test_input($_POST['age']));
$hearaboutus = strval(test_input($_POST['hearaboutus']));
$_SESSION['firstname'] = $firstName;
$_SESSION['lastName'] = $lastName;
$_SESSION['emailFrom'] = $emailFrom;
$_SESSION['phone'] = $firstNaphoneme;
$_SESSION['message'] = $message;
$_SESSION['occupation'] = $occupation;
$_SESSION['age'] = $age;
$_SESSION['hearaboutus'] = $hearaboutus;
$mailTo = "gansaikhanshur#gmail.com";
$subjectLine = "E-Mail From: ".$emailFrom."; www.gansaikhanshur.com";
$emailBody = "You have received an email from ".$firstName."\n\n".$message."\n\n\n";
mail($mailTo, $subjectLine, $emailBody);
header("Location: thankupage.php");
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
thankupage.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Thank You Page!</title>
<link rel="stylesheet" type="text/css" href="css/support.css">
</head>
<body>
<div class="center">
<p>Thank You <?php
include 'contactform.php';
echo $_SESSION['firstname'];
session_destroy();
?></p>
Go Back
</div>
</body>
</html>
css
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body, html {
background: #DCD8D7;
height: 100%;
font-family: Helvetica, sans-serif;
}
p {
font-family: Helvetica;
font-size: 14px;
line-height: 1.7;
color: #616060;
margin: 0px;
}
input {
outline: none;
border: none;
}
textarea {
outline: none;
border: none;
}
.container {
width: 100%;
min-height: 100vh;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
padding: 10px;
background: transparent;
position: relative;
}
.form-wrap {
width: 770px;
background: #fff;
border-radius: 10px;
overflow: hidden;
position: relative;
}
.contact-title {
width: 100%;
position: relative;
z-index: 1;
display: flex;
flex-wrap: wrap;
flex-direction: column;
align-items: center;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
padding: 64px 15px 64px 15px;
}
.contact-title::before {
content: "";
display: block;
position: absolute;
z-index: -1;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: rgba(54,84,99,0.7);
}
.contact-form {
width: 100%;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
padding: 43px 88px 57px 190px;
}
.div-input-form {
width: 100%;
position: relative;
border-bottom: 1px solid #b2b2b2;
margin-bottom: 26px;
}
.input-label {
font-family: Helvetica;
font-size: 15px;
color: #808080;
line-height: 1.2;
text-align: right;
position: absolute;
top: 14px;
left: -105px;
width: 80px;
}
.user-input {
font-family: Helvetica;
font-size: 15px;
color: #525050;
line-height: 1.4;
display: block;
width: 100%;
background: transparent;
padding: 0 5px;
}
input.user-input {
height: 45px;
}
textarea.user-input {
min-height: 115px;
padding-top: 14px;
padding-bottom: 13px;
}
.div-submit-button {
width: 100%;
display: flex;
flex-wrap: wrap;
padding-top: 8px;
}
.submit-button {
display: flex;
justify-content: center;
align-items: center;
padding: 0 20px;
min-width: 160px;
width: 100%;
height: 50px;
background-color: #3b88bb;
border-radius: 25px;
font-family: Helvetica;
font-size: 16px;
color: white;
line-height: 1.2;
}
.radio-radio
{
-webkit-appearance: none;
appearance: none;
display: inline-block;
position: relative;
background-color: #f1f1f1;
color: rgb(92, 91, 91);
top: 10px;
height: 25px;
width: 25px;
border: 0;
border-radius: 40px;
cursor: pointer;
margin-right: 7px;
outline: none;
}
.radio-radio:checked::before
{
position: absolute;
font: 13px/1 'Open Sans', sans-serif;
left: 8px;
top: 5px;
content: '\02143';
transform: rotate(40deg);
}
.checkbox
{
border-radius: 5px;
display: inline-block;
margin-right: 7px;
height: 10px;
width: 10px;
}
.select-occ {
display: block;
font-size: 14px;
font-family: sans-serif;
font-weight: 700;
color: rgb(53, 51, 51);
line-height: 1.5;
padding: 7px;
width: 100%;
max-width: 100%;
box-sizing: border-box;
margin: 0;
border: 1px solid #aaa;
box-shadow: 0 1px 0 1px rgba(0,0,0,.04);
border-radius: 10px;
-moz-appearance: none;
-webkit-appearance: none;
background-color: #fff;
background-repeat: no-repeat, repeat;
background-position: right .7em top 50%, 0 0;
background-size: .65em auto, 100%;
}
#circle-container {
display: flex;
align-items: center;
justify-content: center;
width: 35vw;
height: 35vh;
position:relative;
}
.circle {
width: 30vh;
height: 30vh;
position: absolute;
border-radius: 50%;
}
#firstLayer {
font-size: 23px;
font-family: "Oswald", sans-serif;
letter-spacing: 1.5px;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-weight: bold;
transition: 1s;
}
#secondLayer {
background-color: #CCCCFF ;
transition: 1s;
opacity: 0.5;
}
#thirdLayer {
background-color: black;
transition: 1s;
opacity: 0.5;
}
#fourthLayer {
background-color: cornflowerblue;
transition: 1s;
opacity: 0.5;
}
#fifthLayer {
background-color: #FFFF99;
transition: 1s;
opacity: 0.5;
}
#circle-effect {
position:relative;
width: 30vh;
height: 30vh;
border-radius: 50%;
overflow: hidden;
}
#circle-effect:hover #secondLayer {
transform: translate(0px, 75px);
}
#circle-effect:hover #thirdLayer {
transform: translate(0px, -75px);
}
#circle-effect:hover #fourthLayer {
transform: translate(75px, 0px);
}
#circle-effect:hover #fifthLayer {
transform: translate(-75px, 0px);
}
Try to do the below change in your contactform.php
Wrong --> $_SESSION['phone'] = $firstNaphoneme;
Right --> $_SESSION['phone'] = $phone;
Also add ob_start() at the beginning of your code
<?php
ob_start();
/*
Your code
*/
?>
Hey Good Evening Jaona,
Please write your javascript validation like this
if(err > 0){
alert("Please Fill the Required Fields");
return false;
}
and then try it definitely work fine with all validation and redirect.
Thanks have a good evening
header("location: thankupage.php");
Thank you
Soumyanjan
I would like my subject to change according to the specific button pressed. Each button represents a different order choice, and changes the value of the h2 tag. I would like the contents of this h2 tag to be the subject of my email in PHP. How do I do this?
// JavaScript Document
// Validating Empty Field
//function check_empty() {
//if (document.getElementById('name').value == "" || document.getElementById('email').value == "") {
//alert("Please fill out all fields.");
//} else {
// alert("Order Successful!");
//}
//}
//Function To Display Popup
function div_show1() {
document.getElementById("ordertype").innerHTML = "$400 Website Order";
document.getElementById('abc').style.display = "block";
}
function div_show2() {
document.getElementById("ordertype").innerHTML = "$500 Website Order";
document.getElementById('abc').style.display = "block";
}
function div_show3() {
document.getElementById("ordertype").innerHTML = "$700 Website Order";
document.getElementById('abc').style.display = "block";
}
//Function to Hide Popup
function div_hide() {
document.getElementById('abc').style.display = "none";
}
#charset "utf-8";
/* CSS Document */
#abc {
width: 100%;
height: 100%;
opacity: 0.97;
top: 0;
left: 0;
display: none;
position: fixed;
background-color: #313131;
overflow: auto;
z-index: 9999999;
}
img#close {
position: absolute;
right: -14px;
top: -14px;
cursor: pointer;
}
div#popupContact {
position: absolute;
left: 50%;
top: 17%;
margin-left: -202px;
font-family: coolfont;
}
form {
max-width: 300px;
min-width: 250px;
padding: 20px 50px;
border: 2px solid gray;
border-radius: 10px;
font-family: coolfont;
background-color: #fff;
}
#moveupwards {
margin-top: -20px;
}
p {
margin-top: 30px;
}
h2 {
background-color: #FEFFED;
padding: 20px 35px;
margin: -10px -50px;
text-align: center;
border-radius: 10px 10px 0 0;
font-family: info;
}
hr {
margin: 10px -50px;
border: 0;
border-top: 1px solid #ccc;
}
input[type=text] {
width: 82%;
padding: 10px;
margin-top: 30px;
border: 1px solid #ccc;
padding-right: 40px;
font-size: 16px;
font-family: coolfont;
}
input[type=email] {
width: 82%;
padding: 10px;
margin-top: 30px;
border: 1px solid #ccc;
padding-right: 40px;
font-size: 16px;
font-family: coolfont;
}
textarea {
width: 82%;
height: 95px;
padding: 10px;
resize: none;
margin-top: 30px;
border: 1px solid #ccc;
padding-right: 40px;
font-size: 16px;
font-family: coolfont;
margin-bottom: 30px;
}
#submit {
text-decoration: none;
width: 100%;
text-align: center;
display: block;
background-color: #FFBC00;
color: #fff;
border: 1px solid #FFCB00;
padding: 10px 0;
font-size: 20px;
cursor: pointer;
border-radius: 5px;
}
#media only screen and (max-width: 457px) {
form {
max-width: 200px;
min-width: 150px;
padding: 10px 50px;
margin-left: 50px;
}
input[type=text] {
padding-right: 30px;
}
textarea {
padding-right: 30px;
}
}
#media only screen and (max-width: 365px) {
form {
max-width: 140px;
min-width: 90px;
padding: 10px 50px;
margin-left: 80px;
}
input[type=text] {
padding-right: 10px;
}
textarea {
padding-right: 10px;
}
}
<a class="button" id="popup" onclick="div_show1()">ORDER NOW</a>
<a class="button" id="popup" onclick="div_show2()">ORDER NOW</a>
<a class="button" id="popup" onclick="div_show3()">ORDER NOW</a>
<div id="abc">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="form.php" id="form" method="post" name="form" enctype="multipart/form-data">
<img id="close" src="images/redcross.png" width="50" onclick="div_hide()">
<h2 id="ordertype" name="ordertype" type="text">#</h2>
<hr>
<div id="moveupwards">
<input id="name" name="name" required="required" placeholder="Name" type="text">
<input id="email" name="email" required="required" placeholder="Email" type="email">
<textarea id="message" name="message" placeholder="Comments/Questions"></textarea>
<input id="submit" name="submit" class="submit" type="submit" value="Order">
</div>
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: -';
$to = 'example#gmail.com';
$subject = $_GET['ordertype'];
$body = "From: ".$name.
"\r\n E-Mail: ".$email.
"\r\n Message: \r\n".$message;
if ($_POST['submit']) {
if (mail($to, $subject, $body, $from)) {
echo '<script>
alert("Order has been placed. We will be in touch with you shortly."); location.href="#";
</script>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
As mentioned by #chris85, <h2> elements are not posted when submitting a form.
You may want to check out the HTML forms guide # MDN.
I suggest populating a hidden <input> with the content of the <h2>.
Something like this demonstration:
function set_value() {
var title = document.getElementById("ordertitle"),
type = document.getElementById("ordertype");
title.innerHTML = type.value = "$400 Website Order";
}
function show_hidden() {
// for demonstration purposes
var type = document.getElementById("ordertype");
type.type="text";
}
document.getElementById("set_value").addEventListener('click',set_value);
document.getElementById("show_hidden").addEventListener('click',show_hidden);
<form action="form.php" method="post" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="ordertype" id="ordertype" />
<h2 id="ordertitle"></h2>
<button id="set_value" >Set Value</button>
<button id="show_hidden">Show Hidden Input</button>
</form>
Also, since you've set your form to method="post", you'll want to retrieve the value from the $_POST array rather than $_GET:
$subject = $_POST['ordertype'];
For reference, see The Post Method.