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);
Related
I'm writing a code that sends email from php with an attachment. And here is my code.
my main.php file
<form action="javascript:postData()" id="form">
<fieldset>
<!-- Form Name -->
<legend>Application</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Full Name">Full Name</label>
<div class="col-md-4">
<input id="FullName" name="FullName" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Email">Email</label>
<div class="col-md-4">
<input id="Email" name="Email" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="roleFor">Role Applying for</label>
<div class="col-md-4">
<input id="roleFor" name="roleFor" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobId">Job ID</label>
<div class="col-md-4">
<input id="jobId" name="jobId" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="uploadResume">Upload Resume</label>
<div class="col-md-4">
<input type="file" name="file" class="form-control">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="experience">Experience</label>
<div class="col-md-4">
<textarea class="form-control" id="experience" name="experience"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" type="submit" name="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
and my js is
function postData() {
const form = document.getElementById('form');
const data = new FormData();
data.append('FullName', form.FullName.value);
data.append('Email', form.Email.value);
data.append('roleFor', form.roleFor.value);
data.append('jobId', form.jobId.value);
data.append('experience', form.experience.value);
fetch('sendEmail.php', {method: 'POST', body: data}).then(response => {
if (!response.ok){
throw new Error('Network response was not ok.');
} else
{
console.log(response);
alert('New job posted');
document.getElementById("form").reset();
}
}).catch(err => console.log(err));
}
and my sendEmail.php is
<?php
$fName = $_POST['FullName'];
$emailAddr = $_POST['Email'];
$roleFor = $_POST['roleFor'];
$jobId = $_POST['jobId'];
$exp = $_POST['experience'];
if (!empty($fName) && !empty($emailAddr))
{
$statusMsg = '';
if (isset($_FILES["file"]["name"]))
{
$emailAddr = $_POST['Email'];
$fromemail = 'admin#admin.com';
$subject = 'Teesst Syubect';
$email_message = "<table><tr><td>Name: </td><td>" . $fName . "</td></tr> </table>";
$email_message .= "Please find CV in the attachment";
$semi_rand = md5(uniqid(time()));
$headers = "From: " . $fromemail;
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
if ($_FILES["file"]["name"] != "")
{
$strFilesName = $_FILES["file"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n";
$email_message .= "--{$mime_boundary}\n" . "Content-Type: application/octet-stream;\n" . " name=\"{$strFilesName}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $strContent .= "\n\n" . "--{$mime_boundary}--\n";
}
$toemail = "myEmail#gmail.com";
if (mail($toemail, $subject, $email_message, $headers))
{
$statusMsg = "Email send successfully with attachment";
header("Location:careers.php");
}
else
{
$statusMsg = "Not sent";
}
}
}
else
{
echo "Enter both Title and Desription";
die();
}
?>
Now the issues are,
when I do <form action="sendEmail.php" id="form" method="post">, it is sending the email as expected, but when I try to post it through javascript (as shown in my code), it isn't sending an email, but to my surprise, the response status is 200 OK.
Please let me know where I'm going wrong.
Thanks
After clicking the submit now button I can't get the message above the form. Please help me out in this. Please anyone.
Here is index.html form:
<form id="contact-form" method="post" action="contact.php">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_need">Please specify your need *</label>
<select id="form_need" name="need" class="form-control" required="required" data-error="Please specify your need.">
<option value="">-----</option>
<option value="Request quotation">Request quotation</option>
<option value="Request order status">Request order status</option>
<option value="Request copy of an invoice">Request copy of an invoice</option>
<option value="Other">Other</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdX5uQUAAAAAEPAP03K3_jafzIdoOFSblSgm2um" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
<input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success btn-send btn-danger-gradiant mt-3 mb-3 text-white border-0 py-2 px-3" value="Send message"><span> SUBMIT NOW <i class="fa fa-paper-plane"></i></span></button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> These fields are required.
</p>
</div>
</div>
</div>
</form>
This is the contactus.js:
$(function () {
window.verifyRecaptchaCallback = function (response) {
$('input[data-recaptcha]').val(response).trigger('change');
}
window.expiredRecaptchaCallback = function () {
$('input[data-recaptcha]').val("").trigger('change');
}
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
This is the contact.php form:
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Demo contact form <demo#domain.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <demo#domain.com>';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = '6LdX5uQUAAAAAEakfeeS4jlKkOjvSaqrawNp4gUD';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
Your message is on the an another page because you use action="contact.php".
Try to remove that part of code.Also remove the portion with form
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<button type="submit" class="btn btn-success btn-send btn-danger-gradiant mt-3 mb-3 text-white border-0 py-2 px-3" onclick="addYourFunctionhere()" value="Send message"><span> SUBMIT NOW <i class="fa fa-paper-plane"></i></span></button>
<script>
function addYourFunctionhere(){
var getform_name= $("#form_name").val()
//and here use ajax to send the var from top
$.ajax({
type: "POST",
url: url,
data: {"username":getform_name},
success: function (data) {
console.log(data);
}
});
}
</script>
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>
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.
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.