form validation not validating - javascript

So I am trying to get validation to work on a simple contact form in the footer of my website, Even if I dont enter any text into any of the fields I get the confirmation message that form is sent.
any ideas would be great, also how can I get my confirmation message to appear inline without taking me onto a new page?
HTML
<div class="container">
<!--Grid column-->
<div class="col-md-8">
<form id ="contact-form" name="contact-form" action="mail.php" method="POST" onsubmit="return validateForm()" >
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-6">
<div class="form-group Custom_contact">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
<label for="name" class="">Name</label>
</div>
</div>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-md-6">
<div class="form-group Custom_contact">
<div class="md-form">
<input type="text" id="email" name="email" class="form-control" placeholder="Email Address">
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<!--Grid column-->
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<div class="col-md-12">
<div class="form-group Custom_contact">
<input type="text" id="subject" name="subject" class="form-control">
<label for="subject" class="">Subject</label>
</div>
</div>
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-12">
<div class="form-group Custom_contact">
<textarea type="text" id="message" name="message" class="form-control" placeholder="Message here"></textarea>
<label for="message">Message</label>
</div>
</div>
</div>
<!--Grid row-->
</div>
</form>
<button class="the-button call-to-button btn-main btn-project" style="background-color: #00ffc4; float: right; margin-top: 0px;">
<a onclick="validateForm()" class="btn-all">Send Message <i class="fa fa-arrow-right"></i></a>
<div class="button-mask"></div>
</a>
</button>
php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$content="From: $name \n Email: $email \n Message: $message";
$recipient = "myemail#gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
echo "Email sent!";
?>
JS
<script>
function validateForm() {
var x = document.getElementById('name').value;
if (x == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
return false;
}
x = document.getElementById('email').value;
if (x == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
return false;
} else {
var 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,}))$/;
if(!re.test(x)){
document.getElementById('status').innerHTML = "Email format invalid";
return false;
}
}
x = document.getElementById('subject').value;
if (x == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
return false;
}
x = document.getElementById('message').value;
if (x == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
return false;
}
document.getElementById('status').innerHTML = "Sending...";
document.getElementById('contact-form').submit();
}
</script>

For a better security and best practices you have to check input validation for both client side and server side.
-> Here is how you can do it with HTML, JavaScript and PHP:
HTML: add 'required' inside the fields that you won't them to be empty and make sure email field type is 'email' not 'text' (type="email")
<div class="container">
<!--Grid column-->
<div class="col-md-8">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-6">
<div class="form-group Custom_contact">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="Name" required>
<label for="name" class="">Name</label>
</div>
</div>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-md-6">
<div class="form-group Custom_contact">
<div class="md-form">
<input type="email" id="email" name="email" class="form-control" placeholder="Email Address" required>
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<!--Grid column-->
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<div class="col-md-12">
<div class="form-group Custom_contact">
<input type="text" id="subject" name="subject" class="form-control" required>
<label for="subject" class="">Subject</label>
</div>
</div>
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-12">
<div class="form-group Custom_contact">
<textarea type="text" id="message" name="message" class="form-control" placeholder="Message here" required></textarea>
<label for="message">Message</label>
</div>
</div>
</div>
<!--Grid row-->
</div>
</form>
<button class="the-button call-to-button btn-main btn-project" style="background-color: #00ffc4; float: right; margin-top: 0px;">
<a class="btn-all">Send Message <i class="fa fa-arrow-right"></i></a>
<div class="button-mask"></div>
</a>
</button>
JAVASCRIPT: use event listener instead of onclick so that you can prevent the form submission and check for empty fields and valid email address without sending data
const contactForm = document.getElementById('contact-form');
if (contactForm) {
contactForm.addEventListener('submit', validateForm);
}
function validateForm(e) {
var x = document.getElementById('name').value;
if (x == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
e.preventDefault();
return;
}
x = document.getElementById('email').value;
if (x == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
e.preventDefault();
return;
} else {
var 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,}))$/;
if (!re.test(x)) {
document.getElementById('status').innerHTML = "Email format invalid";
e.preventDefault();
return;
}
}
x = document.getElementById('subject').value;
if (x == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
e.preventDefault();
return;
}
x = document.getElementById('message').value;
if (x == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
e.preventDefault();
return;
}
document.getElementById('status').innerHTML = "Sending...";
}
PHP: Checking data is sent, then using htmlspecialchars func to Convert special characters to HTML entities OR strip_tags func to Strip HTML and PHP tags from a string and finally using filter_var to check email validation.
<?php
// Checking for sent fields
if(!isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['subject'])){
echo "Error! You have to fill in all required fields";
exit();
}
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
$subject = htmlspecialchars($_POST['subject']);
// Checking for empty fields
if(empty($name) || empty($email) || empty($message) || empty($subject)){
echo "Error! You have to fill in all required fields";
exit();
}
// Check email validation
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Error! Email address considered invalid.";
exit();
}
$content="From: $name \n Email: $email \n Message: $message";
$recipient = "myemail#gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
echo "Email sent!";
?>

You can use the required parameter in your input field like:
<input type="text" id="name" name="name" class="form-control" placeholder="Name" required>
Also in your email input field you can use the type email so you can also have email validation input in this field
<input type="email" id="email" name="email" class="form-control" placeholder="Email Address" required>

Related

HTML/CSS/JavaScipt and Email Configuration with PHP. Email not sending? Only prompts button as "Sending..." and then nothing happens

I am trying to send an email with PHP, but it isn't working. I think my code is correct, but I am having troubles connecting to the back-end server from my iMac computer. The form just says "Sending..." and I get no email.
What I tried:
Downloaded XAMPP and put the whole code in the htdocs folder.
Followed the prompts and installed packages to "Send Email with PHP" on the XAMPP website.
Downloaded Node.js and Express.
Tried to put file in localhost directory (not working). This is where it is located: file:///Applications/XAMPP/xamppfiles/htdocs/constructioncompany-master/public/index.html
Tried to click "Send" button and check the console.log simultaneously, and nothing happens. It's still loading with "Sending"
Checked my spam email inbox to see if it sent there.
Checked the error log in XAMPP and it says this, but not sure if this is relevant (I am new with PHP):
[Sun Jan 29 19:11:11.379312 2023] [php:error] [pid 64583] [client ::1:55351] script '/Applications/XAMPP/xamppfiles/htdocs/contact_process.php' not found or unable to stat
contact.html
<div class="row">
<div class="col-12">
<h2 class="contact-title">SEND US A MESSAGE</h2>
</div>
<div class="col-lg-8">
<form class="form-contact contact_form" action="contact_process.php" method="post" id="contactForm" novalidate="novalidate">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input class="form-control valid" name="name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your name'" placeholder="Enter your name" required="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input class="form-control valid" name="email" id="email" type="email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your email'" placeholder="Enter your email" required="'">
</div>
</div>
<div class="col-12">
<div class="form-group">
<input class="form-control" name="subject" id="subject" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter subject'" placeholder="Enter subject" required="">
</div>
</div>
<div class="col-12">
<div class="form-group">
<textarea class="form-control w-100" name="message" id="message" cols="30" rows="9" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your message'" placeholder="Write your message" required=""></textarea>
</div>
</div>
</div>
<div class="form-group mt-3">
<button type="submit" id="send" class="button boxed-btn">Send</button>
</div>
</form>
</div>
<div class="col-lg-3 offset-lg-1">
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-home"></i></span>
<div class="media-body">
<h3>San Francisco, CA, USA</h3>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-tablet"></i></span>
<div class="media-body">
<h3>828-450-2288</h3>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-email"></i></span>
<div class="media-body">
<h3>handtfloors#gmail.com</h3>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-facebook"></i></span>
<div class="media-body">
<li>#SanFranciscoFloors</li>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-instagram"></i></span>
<div class="media-body">
<li>#handtflooring</li>
</div>
</div>
</div>
PHP File
<?php
class Sendmail{
function getMailStatus(){
//Check For Submit
$status = '';
//Get Form Data
$name = htmlspecialchars($_POST['name']);
$phone = htmlspecialchars($_POST['phone']);
$email = htmlspecialchars($_POST['email']);
$title = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message']);
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$status = '3';
} else {
// Passed
// Recipient Email
$toEmail = 'myemailaddress#gmail.com';
$subject = ''.$title;
$body = '<h2>H & T Flooring Contact Request</h2>
<h4>Name</h4><p>'.$name.'</p>
<h4>Phone Number</h4><p>'.$phone.'</p>
<h4>Email</h4><p>'.$email.'</p>
<h4>Message</h4><p>'.$message.'</p>
';
//Email Headers
$headers ="MIME-Version: 1.0" ."\r\n";
$headers .="Content-Type:text/html;charset=UTF-8" . "\r\n";
// Additional Headers
$headers .= "From: " .$name. "<".$email.">". "\r\n";
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$status = '1';
} else {
//Failed
$status = '2';
}
}
return $status;
}
}
$test = new Sendmail();
echo $test->getMailStatus();
?>
contact.js
$(document).ready(function(){
$("#send").on('click', function(e){
$("#send").text('Sending...');
$("#send").attr('disabled', true);
$.ajax({
url: "/Applications/XAMPP/xamppfiles/htdocs/constructioncompany-master/public/contact_process.php",
method:"POST",
dataType:"JSON",
data:{
name:$("#name").val(),
email:$("#email").val(),
phone:$("#phone").val(),
subject:$("#subject").val(),
message:$("#message").val()
},
success:function(res){
$("#send").text('Send');
$("#send").attr('disabled', false);
if (res == 1){
$("#status").html('Message Sent Successfully! Thank you for contacting us. We will get back to you as soon as possible.');
}else if(res == 0){
$("#status").html('Message Failed.');
}else if(res == 2){
$("#status").html('Empty Fields Detected.');
}else if(res == 3){
$("#status").html('Invalid Email Address.');
}
},
error: function(err){
$('#status').html( "Network Connection Error.");
}
});
});
});
app.js
const express = require("express");
const app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.listen(3000, function () {
console.log("Server is running on localhost3000");
});

Contact us form isn't sending all populated fields to email, only a few? PHP AJAX JS

So I've gone through a thread that helped me build this contact us form, but it talked about validating and making the fields required. There are two fields I have in my form that doesn't need to be required $organization and $budget, I can't seem to get the information in there to send with the email. The email shows those fields as blank but the other fields are populated.
I have practically zero experience in PHP outside of this form.
Expected output:
Name: xxx
Email: xxx#xxx.com
Organization: xxx
Budget: xxx
Message: xxx
What I actually receive in my email:
Name: xxx
Email: xxx#xxx.com
Organization:
Budget:
Message: xxx
Code:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "example#mydomain.com";
$Subject = "Received msg from WIP contact form";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Organization: ";
$Body .= $organization;
$Body .= "\n";
$Body .= "Budget: ";
$Body .= $budget;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Sorry, something went wrong.";
} else {
echo $errorMSG;
}
}
?>
HTML:
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" placeholder="$50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JavaScript:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Please fill in the required fields.");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var organization = $("#organization").val();
var budget = $("#budget").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message + "&organization=" + organization + "&budget" + budget,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "We'll be in touch with you soon!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
EDIT
Thanks to Uxmal for suggesting the name="xxxx" in the input field. He said that by doing this, the $_POST is looking for inputs with name. Which made me realise I must be doing something else wrong. Turns out my ajax was poorly written and I was also missing the <form action aswell. Below is the corrected version of the form and ajax code.
<form action="form-process.php" method="POST" role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization name">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" name="budget" placeholder="50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" name="message" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JS:
function submitForm(){
$.ajax({
type: "POST",
url: "php/form-process.php",
data: $('#contactForm').serialize(),
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}
You PHP code at line
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
looks for inputs with name: organization and budget, no to for id organization and budget.
At you html is
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" placeholder="$50000">
without a tag: name="organization" and tag: name="budget".
So put those tags like
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" name="budget" placeholder="$50000">
and then your PHP code will get the data.

First time using prepared statements but query is not activating

I have just started using prepared statements as it was brought to my attention by another user. However, after I started to implement it, it doesn't seem to properly add the new record to the database. When I click on Submit, it just shows the register success div that I have setup.
login.php (Where the form is located)
<form id="signupform" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-3 control-label">Email</label>
<div class="col-md-9">
<input type="text" class="form-control" name="email" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="firstname" class="col-md-3 control-label">First Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="firstname" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-md-3 control-label">Last Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="lastname" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="age" class="col-md-3 control-label">Age</label>
<div class="col-md-9">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' maxlength="3" class="form-control" name="age" placeholder="Age">
</div>
</div>
<div class="form-group">
<label for="region" class="col-md-3 control-label">Region</label>
<div class="col-md-9">
<input type="text" class="form-control" name="region" placeholder="Region">
</div>
</div>
<div class="form-group">
<label for="address" class="col-md-3 control-label">Address</label>
<div class="col-md-9">
<input type="text" class="form-control" name="address" placeholder="Address">
</div>
</div>
<div class="form-group">
<label for="Postcode" class="col-md-3 control-label">Postcode</label>
<div class="col-md-9">
<input type="text" class="form-control" name="postcode" placeholder="Postcode">
</div>
</div>
<div class="form-group">
<label for="language" class="col-md-3 control-label">Language</label>
<div class="col-md-9">
<input type="text" class="form-control" name="language" placeholder="Language">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<button id="btn-signup" type="submit" class="btn btn-info"><i class="icon-hand-right"></i>Submit</button>
</div>
</div>
</form>
JavaScript:
<script type="text/javascript">
$(function() {
$("#signupform").bind('submit',function() {
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var age = $('#age').val();
var region = $('#region').val();
var address = $('#address').val();
var postcode = $('#postcode').val();
var language = $('#language').val();
$.post('scripts/register.php',{username:username, email:email, password:password, firstname:firstname, lastname:lastname, age:age, region:region, address:address, postcode:postcode, language:language}, function(data){
$('#signupsuccess').show();
}).fail(function(){{
$('#signupalert').show();
}});
return false;
});
});
</script>
register.php
<?php
include 'connection.php';
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO `users` (`ID`, `Username`, `Password`, `Email`, `First_Name`, `Last_Name`, `Age`, `Region`, `Address`, `Postcode`, `Language`) VALUES ('NULL', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
$stmt->bind_param(NULL, $username, $password, $email, $firstName, $lastName, $age, $region, $address, $postcode, $language);
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
$region = $_POST['region'];
$address = $_POST['address'];
$postcode = $_POST['postcode'];
$language = $_POST['language'];
$stmt->execute();
$stmt->close();
?>
You're getting values from elements you think have id's (like #username) but none of your inputs has id="username". You can either add the id's to your input elements or you can change your selectors, e.g. $('[name="username"]')

php doesn't add a div, it changes the page completely

I am trying to make a contact form in PHP and HTML. The code works but the problem is that is completely changes the page simply ruining the process of having only a single change: the div that goes on the bottom of the form. Here is my php file:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$title = $_POST['title'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$url = $_POST['url'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Partner from Website';
$to = 'jordanwhite916#gmail.com';
$subject = 'VetConnexx Partner Inquiry';
$body = "From: $name\n E-Mail: $email\n Phone: $phone\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
if (!$_POST['title']) {
$errTitle = 'Please enter your title';
}
if (!$_POST['phone']) {
$errPhone = 'Please enter your phone';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['url'] || !filter_var($_POST['url'], FILTER_VALIDATE_URL)) {
$errURL = 'Please enter a valid website';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman && !$errTitle && !$errPhone && !$errURL) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="success">Thank You! I will be in touch</div>';
} else {
$result='<div class="danger">Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
<div class="panel panel-default">
<div class="panel-body">
<p>Become a VetConnexx Business Partner.</p>
<br />
<br />
<p>VetConnexx brings the mission focused discipline, integrity, and motivation of the US Armed Forces
to your customers. VetConnexx has been tested by the best and exceeds the standards expected of
Fortune 100 companies and their privately held peers.</p>
<br />
<br />
<p>We can bring the same level of service to your business. To discuss our client services, please
contact us at VetPartners#VetConnexx.com</p>
<br />
<br />
<form class="form-horizontal" role="form" method="post" action="businesspartners.php">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="<?php echo htmlspecialchars($_POST['title']); ?>">
<?php echo "<p class='text-danger'>$errTitle</p>";?>
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone" value="<?php echo htmlspecialchars($_POST['phone']); ?>">
<?php echo "<p class='text-danger'>$errPhone</p>";?>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-2 control-label">URL</label>
<div class="col-sm-10">
<input type="url" class="form-control" id="url" name="url" placeholder="www.examplewebsite.com" value="<?php echo htmlspecialchars($_POST['url']); ?>">
<?php echo "<p class='text-danger'>$errURL</p>";?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="message" placeholder="How may we help you?"><?php echo htmlspecialchars($_POST['message']);?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
<?php echo "<p class='text-danger'>$errHuman</p>";?>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
The link to the website I am trying to develop is located here: Go to Business Partners, and fill out the information in the contact form to see what may be wrong. I only want the div on the bottom to show after the Send button is click, not for a completely white page with black text and forms to come up that has the same content. Here's the link to the website:
http://www.sampsonvision.com/VetConnexxWebsite
I suggest you want to use AJAX call to your PHP file instead of a simple submission. Because after form submission, the only content appears on a page is that one which was generated by the script. Your script outputs only one div.

PHPmailer not sending mail in only Firefox

I'm having a bit of an issue with my PHPmailer service. I've tested it multiple times in Internet Explorer and Chrome. It works great. It just doesn't send anything when I try Firefox.
My domain shows it has PTR set up as well. I've checked the logs, and I've gotten no problems. Kind of at a loss for what to do.
HTML:
<div class = "myBox" ng-show="isSet(3)" ng-controller="ContactController">
<!-- Name, Company, Title, Address, City, State, County, Phone, Email, Type of request(new equipment or other pics), select one(item), comments -->
<h2 class="topProductTitle"><b>Request a Quote:</b></h2><br>
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Name" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputCompany.$invalid && submitted }">
<label for="inputCompany" class="col-lg-2 control-label">Company</label>
<div class="col-lg-10">
<input ng-model="formData.inputCompany" type="text" class="form-control" id="inputCompany" name="inputCompany" placeholder="Company" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputTitle.$invalid && submitted }">
<label for="inputTitle" class="col-lg-2 control-label">Title</label>
<div class="col-lg-10">
<input ng-model="formData.inputTitle" type="text" class="form-control" id="inputTitle" name="inputTitle" placeholder="Title" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputAddress.$invalid && submitted }">
<label for="inputAddress" class="col-lg-2 control-label">Address</label>
<div class="col-lg-10">
<input ng-model="formData.inputAddress" type="text" class="form-control" id="inputAddress" name="inputAddress" placeholder="Address" maxlength="40" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputCity.$invalid && submitted }">
<label for="inputCity" class="col-lg-2 control-label">City</label>
<div class="col-lg-10">
<input ng-model="formData.inputCity" type="text" class="form-control" id="inputCity" name="inputCity" placeholder="City" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputState.$invalid && submitted }">
<label for="inputState" class="col-lg-2 control-label">State</label>
<div class="col-lg-10">
<input ng-model="formData.inputState" type="text" class="form-control" id="inputState" name="inputState" placeholder="State" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputPhone.$invalid && submitted }">
<label for="inputPhone" class="col-lg-2 control-label">Phone</label>
<div class="col-lg-10">
<input ng-model="formData.inputPhone" type="tel" class="form-control" id="inputPhone" name="inputPhone" placeholder="Phone" maxlength="15" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary btn-md" ng-disabled="submitButtonDisabled">
<h4>Send Message</h4>
</button>
</div>
</div>
</form>
</div>
Angular:
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the data.
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform)
{
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed! Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
PHP:
<?php
require_once 'PHPMailer-master/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('test2#gmail.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nCompany: " . stripslashes($_POST['inputCompany']) ."\r\n\r\nTitle: " . stripslashes($_POST['inputTitle']) . "\r\n\r\nAddress: " . stripslashes($_POST['inputAddress'])
. "\r\n\r\nCity: " . stripslashes($_POST['inputCity']) . "\r\n\r\nState: " . stripslashes($_POST['inputState']) . "\r\n\r\nPhone: " . stripslashes($_POST['inputPhone']) . "\r\n\r\nEmail: " . stripslashes($_POST['inputEmail'])
. "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "Test#gmail.com";
$mail->Password = "123";
$mail->setFrom('Test#gmail.com', 'Contact Form');
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit();
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
I have exactly the same thing. My mailer works with Chrome and Edge, but not Firefox. This cut-down code, called from the address bar, behaves the same:
$subject="FIREFOX test";
$scrnmess = "Howdee doodee";
$email="canthaveit.com";
$recipient="webmaster#waterfowl.org.uk";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: " . $email . "\r\n";
mail($recipient, $subject, $scrnmess, $headers);

Categories

Resources