I am looking to use reCaptcha with the jquery '.load' ajax function so that the information is passed across to my PHP contact form. I have established how to send across things such as name value, subject value etc with this method, however, I am unsure how to pass across the reCaptcha info.
As it currently stands when I submit the form I receive a PHP error advising 'Undefined index: g-recaptcha-response'. I believe this is to do with the Ajax side of things.
Any help on this would be amazing as I am at a total loss!
jQuery:
$("#contactForm").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var phone = $("#phone").val();
var company = $("#company").val();
var message = $("#message").val();
var submit = $("#submit").val();
$(".form-message").load("contactForm.php", {
name: name,
email: email,
subject: subject,
phone: phone,
company: company,
message: message,
submit: submit
});
PHP:
if(isset($_POST['submit'])) {
require 'dist/PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$message = $_POST['message'];
$secretKey = "--KEY--";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$mail->HOST = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = '--username--';
$mail->Password = '--password--';
$mail->setFrom('--email--', 'Contact Form Submission');
$mail->addAddress('--email--');
$mail->addReplyTo($email, $name);
$mail->isHTML(true);
$mail->Subject= $subject;
$mail->Body='<p>Name: '.$name. '<br>Email: '.$email.'<br>Subject: '.$subject.'<br>Phone: '.$phone.'<br>Company: '.$company.'<br>Message: '.$message.'</p>';
HTML:
<form method="POST" action="contactForm.php" id="contactForm">
<div class="form-group">
<input
type="text"
id="name"
name="name"
class="form-control"
placeholder="Full Name"
/>
</div>
<div class="form-group">
<input
type="text"
id="email"
name="email"
class="form-control"
placeholder="Email Address"
/>
</div>
<div class="form-group">
<input
type="text"
id="subject"
name="subject"
class="form-control"
placeholder="Subject"
/>
</div>
<div class="form-group">
<input
id="phone"
type="text"
name="phone"
class="form-control"
placeholder="Phone (optional)"
/>
</div>
<div class="form-group">
<input
id="company"
type="text"
name="company"
class="form-control"
placeholder="Company (optional)"
/>
</div>
<div class="form-group">
<textarea
class="form-control"
id="message"
name="message"
placeholder="Message"
style="height: auto"
rows="5"
></textarea>
</div>
<div
class="g-recaptcha"
data-sitekey="--KEY--"
></div>
<input
id="submit"
type="submit"
value="Submit"
class="btn btn-outline-primary btn-block mb-3"
name="submit"
/>
</form>
You can use the grecaptcha.getResponse() method to get the value of the captcha from the client side, then send that value with your ajax/jquery
<script type="text/javascript">
("#contactForm").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var phone = $("#phone").val();
var company = $("#company").val();
var message = $("#message").val();
var submit = $("#submit").val();
var captcha = grecaptcha.getResponse(); //get captcha
$(".form-message").load("contactForm.php", {
name: name,
email: email,
subject: subject,
phone: phone,
company: company,
message: message,
submit: submit,
captcha : captcha
});
</script>
Then your php
<?php
if(isset($_POST['submit'])) {
require 'dist/PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$message = $_POST['message'];
$secretKey = "--KEY--";
$responseKey = $_POST['captcha']; //captcha
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$mail->HOST = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = '--username--';
$mail->Password = '--password--';
$mail->setFrom('--email--', 'Contact Form Submission');
$mail->addAddress('--email--');
$mail->addReplyTo($email, $name);
$mail->isHTML(true);
$mail->Subject= $subject;
$mail->Body='<p>Name: '.$name. '<br>Email: '.$email.'<br>Subject: '.$subject.'<br>Phone: '.$phone.'<br>Company: '.$company.'<br>Message: '.$message.'</p>';
Related
I am new to php but I would like to use a phpmailer in my project. I have followed the steps from here: https://github.com/PHPMailer/PHPMailer but the form somehow does not send and I get a 404 problem. Can anyone help me understand what it is that I am doing wrong here?
My html file:
<div class="container">
<form method="POST" action="form.php">
<div class="section7">
<div>
<input type="text" name="company" placeholder="Firma*" required><br>
<input type="text" name="surname" placeholder="Nazwisko*" required><br>
<input type="email" name="email" placeholder="E-mail*" required><br>
<textarea name="message" placeholder="Wiadomość*" required></textarea>
</div>
<div>
<input type="text" name="address_code" placeholder="Kod pocztowy*" required><br>
<input type="text" name="name" placeholder="Imię*" required><br>
<input type="tel" name="phone" placeholder="Nr telefonu*" required>
</div>
</div>
<div class="checkbox">
<label for="policy"></label><input type="checkbox" id="policy" name="policy" value="policy" required>
</label>Wyrażam zgodę na przetwarzanie moich danych osobowych zgodnie z ustawą z dnia 29.08.1997 (Dz.U.nr 133,poz.883) o ich ochronie.</label><br>
</div>
<div class="btn-submit">
<input type="submit" value="Wyślij">
</div>
</form>
</div>
My php form file:
<?php
require_once('mailer/class.phpmailer.php');
require_once('mailer/class.smtp.php');
require_once('mailer/PHPMailerAutoload.php');
require_once('phpmaileroauthgoogle.php');
header('Content-Type: application/json');
$mail = new PHPMailer(true);
try {
$name = $_POST['name'];
$surname = $_POST['surname'];
$company = $_POST['company'];
$email = $_POST['email'];
$tel = $_POST['phone'];
$address = $_POST['address_code'];
$messageText = $_POST['message'];
if (empty($name) || empty($email) || empty($tel) || empty($messageText) || empty($surname) || empty($company) || empty($address)) {
http_response_code(400);
echo json_encode("All fields are required.");
exit;
}
$messageText .= "\nNumer telefonu: " . $tel;
$mail->isSMTP();
$mail->CharSet = "UTF-8";
$mail->FromName = "$name";
$mail->Host = "smtp.gmail.com";
$mail->Mailer = "smtp";
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->SMTPAutoTLS = false;
$mail->Username = "myemail";
$mail->Password = "mypassword";
$mail->SetFrom("myemail");
$mail->Subject = "Message sent from xxx website";
$mail->Body = $messageText;
$mail->AddAddress("myemail");
$mail->AddReplyTo($email);
if ($mail->send()) {
echo json_encode("Thank you the message has been sent.");
} else {
http_response_code(400);
echo json_encode("Sorry, there was an error");
}
} catch (\Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
I am trying to build an inquiry form and send the data to my email using PHPMailer. I am receiving the data which is submitted through the form but I am not able to send a confirmation to the customer who filled the form. So far this is my form:
<form class="myForm" action="" id="iForm" method="POST">
<input type="text" id="Name" placeholder="Name" required>
<input type="email" id="Email" placeholder="Email" required>
<input type="tel" id="Phone" placeholder="Phone Number" required>
<input type="text" id="Date" placeholder="Schedule a call" required>
<textarea id="Message" rows="5" placeholder="Your Message" required></textarea>
<div class="form-group">
<button type="submit" class="btn cbtn">SUBMIT</button>
</div>
</form>
Passing the data from the submitted form
$("#iForm").on('submit', function(e) {
e.preventDefault();
var data = {
name: $("#Name").val(),
email: $("#Email").val(),
phone: $("#Phone").val(),
date: $("#Date").val(),
message: $("#Message").val()
};
if ( isValidEmail(data['email']) && (data['name'].length > 1) && (data['date'].length > 1) && (data['message'].length > 1) && isValidPhoneNumber(data['phone']) ) {
$.ajax({
type: "POST",
url: "php/appointment.php",
data: data,
success: function() {
$('.success.df').delay(500).fadeIn(1000);
$('.failed.df').fadeOut(500);
}
});
} else {
$('.failed.df').delay(500).fadeIn(1000);
$('.success.df').fadeOut(500);
}
return false;
});
Checking for valid email address
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
Checking for a valid phone number
function isValidPhoneNumber(phoneNumber) {
return phoneNumber.match(/[0-9-()+]{3,20}/);
}
This is the code which I am using from PHPMailer:
$_name = $_REQUEST['name'];
$_email = $_REQUEST['email'];
$_phone = $_REQUEST['phone'];
$_date = $_REQUEST['date'];
$_message = $_REQUEST['message'];
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->Username = "office#myhost.co.uk";
$mail->Password = "********";
$mail->Host = "myhost.co.uk";
$mail->setFrom('office#myhost.co.uk', 'Alex');
$mail->addAddress('me#gmail.com', 'Alex');
$mail->isHTML(true);
$mail->Subject = 'New inquiry from CC';
$mail->Body = <<<EOD
<strong>Name:</strong> $_name <br>
<strong>Email:</strong> $_email <br> <br>
<strong>Phone:</strong> $_phone <br>
<strong>Booking Date:</strong> $_date <br>
<strong>Message:</strong> $_message <br>
I've tried using this, making another instance of PHPMailer and Send the email to the customer with the email they provided.
if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->setFrom('office#myhost.co.uk', 'Alex');
$autoRespond->AddAddress($_email);
$autoRespond->Subject = "Autorepsonse: We received your submission";
$autoRespond->Body = "We received your submission. We will contact you";
$autoRespond->Send();
}
I've tried a few online "solutions" to this with no success. Any ideas ?
I finally found the solution of my issue. Basically everything above is correct the only thing which I missed was pass the SMTP parameters again to the new instance of PHPMailer. So now the last piece of code which caused the issue looks like that:
if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->IsSMTP();
$autoRespond->CharSet = 'UTF-8';
$autoRespond->SMTPDebug = 0;
$autoRespond->SMTPAuth = TRUE;
$autoRespond->SMTPSecure = "tls";
$autoRespond->Port = 587;
$autoRespond->Username = "office#myhost.co.uk";
$autoRespond->Password = "********";
$autoRespond->Host = "myhost.co.uk";
$autoRespond->setFrom('office#myhost.co.uk', 'Alex');
$autoRespond->addAddress($_email);
$autoRespond->Subject = "Autorepsonse: We received your submission";
$autoRespond->Body = "We received your submission. We will contact you";
$autoRespond->Send();
}
Thank you for the help everyone.
I have a problem with PHPMailer on my website. In short, I want someone who wants to contact me to be able to send me an e-mail via contact form on my website. Said code looks like this:
index.html:
<form action="formularzeng.php" method="POST">
<div class="form-group">
<label for="InputEmail">E-mail address</label>
<input type="email" class="form-control" id="InputEmail" placeholder="E-mail" name="email">
</div>
<div class="form-group">
<label for="InputName">Full name</label>
<input type="name" class="form-control" id="InputName" placeholder="Full name" name="name">
</div>
<div class="form-group">
<label for="InputText">Message</label>
<textarea id="InputText" class="form-control" rows="5" placeholder="Message" name="message"></textarea>
</div>
<input type="submit" class="btn btn-default" value="Send" name="submit">
</form>
And formularzeng.php looks like this:
<!DOCTYPE html>
<?php
$to = "example#gmail.com";
$from = $_POST['email'];
$name = $_POST['name'];
$subject = "Contact form";
$message = $name . " " . " wrote:" . "\n\n" . $_POST['message'];
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'example#gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('example#gmail.com', 'Mailer');
$mail->addAddress('$to',);
$mail->addReplyTo('$from', 'Mailer');
$mail->isHTML(true);
$mail->Subject = '$subject';
$mail->Body = '$message';
$mail->AltBody = '$message';
And a html section below with all the content saying "Thank you for your message. After uploading all the files on the server, filling the form and clicking on "Send" all I get is a white page, without any content. I'm totally green with php, but I want a working form on my portfolio website. Why is it not working?
Change all of your '$var_name' to "$var_name" to make PHP parse your strings....
For example, turn this :
$mail->Subject = '$subject';
$mail->Body = '$message';
$mail->AltBody = '$message';
Into :
$mail->Subject = "$subject";
$mail->Body = "$message";
$mail->AltBody = "$message";
Turn out it was one coma too much in line:
$mail->addAddress('$to',);
removing it fixed the problem, now it's
$mail->addAddress('$to');
And it works.
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!";
}
}
?>
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').