$_FILES is empty in form - php

I have the following form which sends its data to a php file which then processes the data and emails it to me. The problem is that I'm trying to upload a document along with the multipart form and it's not working. It sends the email just without the attachment. The weird thing is it used to work, but I'm not sure what I changed. $_FILES in the PHP form is always empty now, which suggests a problem with my html and not the PHP. I have been through the possible solutions in this link, but none of them worked for me. Can anyone see what's wrong with this form?
<form id="pre-register-contact-form" action="preregisterform.php" method="post" enctype="multipart/form-data" role="form">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<label for="name">Name*</label>
<input required="required" name="name" type="text" class="form-control" id="name" placeholder="Enter your full name" data-error="Please make sure you've entered your name.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="age">Age</label>
<input name="age" type="number" class="form-control" id="age" placeholder="Enter your age">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="email">Email address*</label>
<input required="required" name="email" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter your email address" data-error="Please make sure you've entered your email address.">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="phone">Phone Number</label>
<input name="phone" type="tel" class="form-control" id="phone" aria-describedby="phoneHelp" placeholder="Enter your phone number">
<small id="phoneHelp" class="form-text text-muted">We'll never share your phone number with anyone else.</small>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="comments">Comments</label>
<textarea name="comments" class="form-control" id="comments" placeholder="Add anything extra that you'd like to tell us about yourself here." rows="3"></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="cv">Upload CV*</label>
<input required="required" name="cv" type="file" accept=".pdf,.doc,.docx" class="form-control-file" id="cv" data-error="Please make sure you've uploaded a CV.">
<small id="cvHelp" class="form-text text-muted" aria-describedby="cvHelp">Please make sure it is in PDF or Word format.</small>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LcxSDgUAAAAAEM5qhjSDGS-Vu9HJSzLiL7yaAIG"></div>
</div>
<input type="submit" class="btn btn-success btn-send" value="Submit">
</div>
</form>
My PHP file is as follows (sensitive info removed):
<?php
// require ReCaptcha class
require('../elements/recaptcha/recaptcha-master/src/autoload.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once('../elements/mail/PHPMailer.php');
require_once('../elements/mail/Exception.php');
require_once('../elements/mail/SMTP.php');
$mail = new PHPMailer(true);
// configure
$sendTo = 'an_email_address_here';
$subject = 'New Pre-Register Contact Form Email';
$fields = array('name' => 'Name', 'age' => 'Age', 'phone' => 'Phone', 'email' => 'Email', 'comments' => 'Comments', 'cv' => 'CV'); // array variable name => Text to appear in the email
$okMessage = 'Thank you for your message. We will be in touch when the right vacancy for you comes up.';
$errorMessage = 'There was an error submitting the form. Please make sure your details are correct and try again.';
$recaptchaSecret = 'Some_alphanumeric_value_here';
// let's do the sending
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 in the config above
// 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
//Server settings
//$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'some_email_address_here'; // SMTP username
$mail->Password = 'a_password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom("an_email_address", "Some_Name");
$mail->addReplyTo($_POST["email"], $_POST["name"]);
$mail->addAddress('an_email_address', 'some_name'); // Add a recipient
// This bit is always false
if (array_key_exists('cv', $_FILES)) {
$file_type = $_FILES['cv']['type'];
if (($file_type != 'application/pdf' || $file_type != 'application/msword')) {
throw new \Exception("Please make sure you are only uploading a PDF or a Word document.");
}
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['cv']['name']));
$file_name = $_FILES['cv']['name'];
$file_size = $_FILES['cv']['size'];
$file_error = $_FILES['cv']['error'];
if (move_uploaded_file($_FILES['cv']['tmp_name'], $uploadfile)) {
$mail->addAttachment(
$uploadfile,
$file_name,
'base64',
$file_type
);
}
}
$emailText = "";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "<b>$fields[$key]:</b> $value<br>";
}
}
$emailText .= "<br><br><span style=\"font-size: 12px; color: grey;\">Email sent via the careers pre-register contact form.</span><br>";
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $emailText;
$mail->AltBody = $emailText;
$mail->send();
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
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'];
}
EDIT
Just remembered I am using AJAX with the form! Here is the JQuery, I think this is causing the problem:
$('#pre-register-contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "preregisterform.php";
$.ajax({
type: "POST",
url: url,
contentType: false,
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) {
$('#pre-register-contact-form').find('.messages').html(alertBox);
$('#pre-register-contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})

When you upload a file with ajax you should use Formdata like this:
$('#pre-register-contact-form').on('submit', function (e) {
var this = $(this);
if (!e.isDefaultPrevented()) {
var url = "preregisterform.php";
$.ajax({
type: "POST",
url: url,
data: new FormData(this),
dataType:'json',
processData: false,
contentType: false,
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) {
$('#pre-register-contact-form').find('.messages').html(alertBox);
$('#pre-register-contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
You can find more detailed information here about how to send/upload files with ajax

Related

Issue with contact form displaying sent message on php rather than in html page

So I have tried searching for this issue and have tried many fixes but I still keep getting the same issue, "Contact form successfully submitted. Thank you, I will get back to you soon!" displays on php page rather than on the contact form html page, Im sure there is something very simple that I'm missing, I keep ending in stupid thought and search loops, I thank you all for any help you can offer.
$(function() {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$("#contact-form").validator();
// when the form is submitted
$("#contact-form").on("submit", function(e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "ebsg.php";
// FOR CODEPEN DEMO I WILL PROVIDE THE DEMO OUTPUT HERE, download the PHP files from
// https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
var messageAlert = "alert-success";
var messageText =
"Your message was sent, thank you. ebgs will get back to you soon.";
// let's compose Bootstrap alert box HTML
var alertBox =
'<div class="alert ' +
messageAlert +
' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
messageText +
"</div>";
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$("#contact-form").find(".message").html(alertBox);
// empty the form
$("#contact-form")[0].reset();
}
return false;
}
});
});
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '6LelY04iAAAAAN',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
// configure
$from = 'ebsg contact form <ebsg#domain.com>';
$sendTo = 'ebsg contact form <email#yahoo.co.uk>';
$subject = 'ebsg contact form message';
$fields = array('name' => 'Name', 'surname' => 'Address', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from ebsg website contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
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'];
}
}
?>
<form id="contact-form" method="post" action="ebsg.php" role="form">
<div class="controls">
<div class="row">
<div class="col-md-6">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required>
</div>
<div class="col-md-6">
<label for="form_lastname">Address *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your address *" required>
</div>
<div class="col-md-6">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required>
</div>
<div class="col-md-6">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
</div>
<div class="col-md-12">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for EBSG *" rows="4" required></textarea>
</div>
<div class="col-md-6">
<div class="message"></div>
<div class="g-recaptcha" data-sitekey="6Lel478655677AACWfJGw0i2SDE9B-dbr-5mD6OHqG"></div>
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
<div class="col-md-6">
<p class="text-muted justify-content-center"><strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>

Why my Bootstrap alert not showing in my form? AJAX

My form is supposed to show an alert, either "success" if the message was sent successfully or "danger" if there was an error, for example incorrect captcha or captcha completion.
The problem is that it doesn't show the alert with the CSS style, it only shows the close button and the error. Could someone tell me what is wrong?
Bootstrap version: 4.1 && PHP version 8.1
HTML:
<form id="contact_form" class="contact-form" action="contact_form/contact_form.php" method="post">
<div class="messages"></div>
<div class="controls two-columns">
<div class="fields clearfix">
<div class="left-column">
<div class="form-group form-group-with-icon">
<input id="form_name" type="text" name="name" class="form-control" placeholder="" required="required" data-error="Write your name.">
<label>Name</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group form-group-with-icon">
<input id="form_email" type="email" name="email" class="form-control" placeholder="" required="required" data-error="Put your email.">
<label>Email</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group form-group-with-icon">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="" required="required" data-error="Write a Subject.">
<label>Subject</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="right-column">
<div class="form-group form-group-with-icon">
<textarea id="form_message" name="message" class="form-control" placeholder="" rows="7" required="required" data-error="And... your message?."></textarea>
<label>Message</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6Lc9oSQcAAAAAMd-JXG26NP1iNzIeNZatd_Eetrv"></div>
<input type="submit" class="button btn-send" value="Send">
</div>
</form>
Code JS:
$(function () {
$('#contact_form').validator();
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact_form/contact_form.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();
}
}
});
return false;
}
});
});
CODE PHP:
<?php
// configure
$from = ''; // Replace it with Your Hosting Admin email. REQUIRED!
$sendTo = ''; // Replace it with Your email. REQUIRED!
$subject = '';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message'); // array variable name => Text to appear in the email. If you added or deleted a field in the contact form, edit this array.
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '';
//get verify response data
$c = curl_init('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$verifyResponse = curl_exec($c);
$responseData = json_decode($verifyResponse);
if($responseData->success):
try
{
$emailText = nl2br("You have new message from Contact Form\n");
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= nl2br("$fields[$key]: $value\n");
}
}
$headers = array('Content-Type: text/html; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
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'];
}
else:
$errorMessage = 'Robot verification failed, please try again.';
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
endif;
else:
$errorMessage = 'Please click on the reCAPTCHA box.';
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
endif;
Thanks in advance.

After sending email with PHPMailer show success/failure message on the same page without reloading or redirecting the page

I have created a simple html & bootstrap contact form which is backed by PHPMailer class to send an email. The program works perfectly till the sending of email. However, it is not showing the success/failure message on the same page and not clearing the fields also.
The code which I have written for my demo program is below. Please append your solutions to the same code rather making another code of your own.
index.html
<form method="post" action="mail.php" id="contact-form" role="form">
<div class="card-header">
<h2 class="font-weight-bold text-center my-4">Contact us</h2>
<p class="text-center mx-auto mb-5">Do you have any questions? Please do not hesitate to
contact us directly. Our team will come back to you within
a matter of hours to help you.</p>
<div class="alert alert-success" id="success-message"><span>Thank you for contacting us. We will
be in touch
soon.</span></div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="form-group ">
<label for="name" class="is-required">Name</label>
<input type="text" name="name" id="name" class="form-control" minlength="3"
required>
</div>
</div>
<div class="col-md-6">
<div class="form-group ">
<label for="email" class="is-required">email</label>
<input type="email" name="email" id="email" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="message" class="is-required">Message</label>
<textarea name="message" id="message" rows="2" class="form-control"
required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="text-center text-md-left">
<input type="hidden" name="action" value="sendEmail" />
<button id="submit-button" name="submit" type="submit" value="Send"
class="btn btn-primary"><span>Send</span></button>
</div>
<div class="status" id="status"></div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="status" id="status"></div>
</div>
</div>
</div>
</form>
jQuery/ajax
<script>
$('form').validate();
$(document).ready(() => {
$('#success-message').hide();
$('form').submit((e) => {
let formData = {
'name': $('#name').val(),
'email': $('#email').val(),
'message': $('#message').val(),
'submit': 1
};
$.ajax({
type: 'POST',
url: 'mail.php',
data: formData,
dataType: 'json',
encode: true
}).done((data) => {
if (data.success) {
$('#success-message').show();
} else {
alert('Something went wrong. Please try again!');
}
});
e.preventDefault();
});
});
</script>
mail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// header('Content-Type: application/json');
if (isset($_POST['submit'])) {
$name = $_POST['name']; // Sender's name
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = $_POST['message']; // Sender's message
$errorEmpty = false;
$errorEmail = false;
if (empty($name) || empty($email) || empty($message)) {
echo "<span class='alert alert-danger'> Name is required.</span>";
$errorEmpty = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='alert alert-danger'> Please try entering a correct email.</span>";
$errorEmail = true;
}
// Instantiate PHPMailer class
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mymail#gmail.com'; // SMTP username
$mail->Password = 'mypass'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('mymail#gmail.com', 'My Name');
$mail->addAddress($email, $name); // Add a recipient
$body = '<p>Hello <strong> Mr. ' . $name . '</strong> <br /><br /> We have received your enquiry "' .$message. '". <br /> We ensure you that the team is working on it. <br /><br /> Thank you. </p>';
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'We received your query.';
$mail->Body = $body;
// $mail->AltBody = strip_tags($body);
$mail->send();
// echo 'Message has been sent';
} catch (Exception $e) {
echo $e->errorMessage();
echo "Mailer Error: " . $mail->ErrorInfo;
}
} else {
echo "There was an error!";
}
?>
Your any help is highly appreciated. Thanks in advance.
You're not really trying here. You're making an XHR, but not even attempting to return the results in a format that will work with that, and neither are you returning an error code that will trigger your error handler. First of all, you need to set the correct content type:
header('Content-type: application/json');
Then handle errors or valid responses apropriately, giving results in JSON format:
} catch (Exception $e) {
//Some other code may be better, but anything other than 2xx will do for jQuery
http_response_code(400);
echo json_encode(['status' => false, 'errormessage' => $e->errorMessage(), 'errorinfo' => $mail->Errorinfo]);
exit;
}
echo json_encode(['status' => true]);
exit;
Note that if your check for isset($_POST['submit']) fails, you should not say anything (you're currently displaying an error) - it's what will happen when they first load the page.

Jquery Ajax, PHPMailer doesn't send emails even if there's no error but works if i use stand alone page with fix values

I have this simple bootstrap form that i run on my localhost, it accepts name email and message and a custom captcha in a form of a math question; On submit i used jquery ajax to fetch the data to emailme.php that contains the phpmailer code.. My problem is, no email was sent even if there's no error and the network status is 200 and i can also see this:
http://localhost/emailme.php?name=myname&email=myemail#gmail.com&message=test
however it works if i just use the phpmailer stand alone code with fixed values. how can i make it work?
HTML:
<form id="emailme" method="post">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="e.g. John Doe">
<span id="err_name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="e.g. example#domain.com">
<span id="err_email" class="text-danger"></span>
</div>
<div class="form-group">
<textarea name="message" id="message" cols="30" rows="10" class="form-control" placeholder="Your message"></textarea>
<span id="err_message" class="text-danger"></span>
</div>
<div class="form-group">
<label for="human">5 + 2 = ?</label>
<input type="text" id="human" name="human" class="form-control" placeholder="Your Answer">
<span id="err_human" class="text-danger"></span>
</div>
<input type="submit" class="btn btn-primary btn-sm" value="Send">
</form>
JQUERY:
$("#emailme").on('submit',function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var human = $("#human").val();
var emailRegex = /(.+)#(.+)\.(com|edu|org|etc)$/g;
if(name!==''&&email!==''&&message!==''&&human!==''){
if(email.match(emailRegex)){
if(human==7){
$.ajax({
url:'emailme.php',
typ:'post',
data:{name:name,email:email,message:message},
success:function(response){
console.log(response);
$("#mail-status").html(response);
$("#emailme")[0].reset();
},
error:function(XMLHttpRequest,textStatus,errorThrown){
console.log(textStatus+errorThrown);
}
});
}
else{
$("#mail-status").html("unable to submit form, you're not human");
}
}
else{
$("#err_email").append("Invalid email format");
}
}
else if(name==''){
$("#err_name").append("Name cannot be empty");
}
else if(email==''){
$("#err_email").append("Email cannot be empty");
}
else if(message==''){
$("#err_message").append("Message cannot be empty");
}
else if(human==''){
$("#err_human").append("Please answer the security question");
}
});
PHP:
<?php
date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php';
// Set the email address submissions will be sent to
$email_address = 'myemail#gmail.com';
// Set the subject line for email messages
$subject = 'Test email from localhost using PHPMailer';
// Check for form submission
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "myemail#gmail.com";
$mail->Password = "mypassword";
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress($email_address, 'myname');
$mail->Subject = $subject;
$mail->Body = 'From:'.$_POST['name'].'(' . $_POST['email'] . ')'.'<p><b>Message</b><br/>' . $_POST['message'] . '</p>';
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
?>

form not passing values to PHPMailer

I have a responsive website built with a basic contact form. I am trying to use PHPHMailer which I have used in the past. For some reason my values from my form are not making it to the PHPMailer. I tested by placing hard coded values in "name", "email", "subject", and "message" and the form will work without problem. I tried using "isset" to make sure the was value before trying to send the mail (I did this because without the "isset" I get an "undefined index" error which tells me there are no values. This code worked fine on my basic form which was not responsive but not on this one. I am stumped. Any advice would be welcome. here is my code for both the html and the PHP. Thanks! *I have updated the code as I have narrowed the problem down to the Java Script. In the HTML the "form id="main-contact-form" is triggering the following js code
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
It is this js that is causing the issue. I am currently trying to figure out why on this end. Thanks for those that tried to help previously.
<form id="main-contact-form" name="contact-form" method="post" action="contact.php">
<div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Name" required="required">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email Address" required="required">
</div>
</div>
</div>
<div class="form-group">
<input type="text" name="subject" class="form-control" placeholder="Subject" required="required">
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control" rows="4" placeholder="Enter your message" required="required"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn-submit">Send Now</button>
</div>
</form>
And my PHP;
<?php
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
$subject = $_REQUEST['subject'];
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'myhost.com';
$mail->SMTPAuth = true;
$mail->Username = 'me#myemail.com';
$mail->Password = 'mypassword';
$mail->SMTPSecure = 'tls';
$mail->From = $email;
$mail->FromName = $name;
$mail->addAddress('me#myemail.com');
$mail->addReplyTo($email);
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
?>
Check this in your code you are missing this name in submit button
<button type="submit" class="btn-submit" name='submit'>Send Now</button>
and replace this
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $_POST['subject'];
with this
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
$subject = $_REQUEST['subject'];
For anyone else having this issue. The solution was pretty simple once I finally figured it out. The main.js template being used does not pass data and type in the ajax code. you need to add type:"POST" and data: form.serialize() to the ajax. see below.
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type:"POST",//new
url: $(this).attr('action'),
data: form.serialize(), //new
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact
you').

Categories