form not passing values to PHPMailer - php

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').

Related

Text area in my php contact form won't work (send)

I've been trying this for a while now, following a few different tutorials and and forum threads. It seems like a simple but i just cannot get the any data from textarea. Input type "name" & "mail" is Ok, it's working. I'll paste my php coding and my form below. Any help would be much appreciated. Thanks.
<section id="forma" >
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<form action="send.php" method="post" enctype="multipart/form-data" id="form_page">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="mail" placeholder="E-mail" required>
<textarea name="comment" id="comment" style="margin: 0px 15px -33px 0px; width: 307px; height: 66px;"></textarea><br>
<label class="uploadbutton">
<div class="button" ></div>
<div class='input'></div>
<input type="file" name="file" onchange="this.previousSibling.previousSibling.innerHTML = this.value"/>
</label>
<button type="submit" class="btn btn2"></button>
</form>
</div>
</div>
</div>
</section>
Php
<?php
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['mail'];
$text = $_POST['message'];
$comment = $_POST['comment'];
echo $comment;
$mail->SMTPDebug = 3;
//$mail->isSMTP();
//$mail->Host = '';
//$mail->SMTPAuth = true;
//$mail->Username = '';
//$mail->Password = '';
//$mail->SMTPSecure = 'ssl';
//$mail->Port = 587;
$mail->setFrom('');
$mail->addAddress('');
//$mail->addAddress('');
//$mail->addReplyTo('', 'Information');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
//$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->isHTML(true);
if(isset($_FILES['file']))
$mail->addAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // Optional name$mail->isHTML(true);
$mail->Subject = '';
$mail->Body = '' .$name . ' ,' .$comment. '<br>: ' .$email.'<br>' .$text;
$mail->AltBody = '';
if(!$mail->send()) {
echo 'Error';
} else {
header('location: thank-you.html');
}
?>
JS
<script>
$ ('form').submit(function(event) {
event.preventDefault();
var data = new FormData();
data.append('name', $(this).find('input[name=\'name\']').val());
data.append('phone', $(this).find('input[name=\'phone\']').val());
data.append('mail', $(this).find('input[name=\'mail\']').val());
data.append('comment',$('#comment').val());
if($(this).attr('id') == 'form_page')
data.append('file', $(this).find('input[name=\'file\']')[0].files[0])
$.ajax({
type: "POST",
url: "send.php",
data: data,
cache: false,
contentType: false,
processData: false,
success: (function(data) {
$(this).find("input").val("");
$('#modal').modal('hide');
$('#modal1').modal('show');
$("form").trigger("reset");
})
});
return false;
});
</script>
your fault is in php code:
replace:
$comment = $_POST['comment']);
with:
$comment = $_POST['comment'];
remove extra bracket
replace $(this).find('input[name=\'comment\']').val() with $('#comment').val() in js file
because you are using textarea input selector which won't work for getting textarea value

PHP mail sending doesn't works with this ajax code but works fine without ajax code, with echo in my php.I want response in same page

My HTML code. Here above the form I want to show the response like Email is sending, and after that Thankyou message.
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name"</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id"></div>
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Your text here"></textarea></div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit"></div>
</form>
My PHP code. When I am using echo and without the ajax its working fine. But The response is coming in sendmail.php page. I want ajax response above the form in html page..
<?php
if(isset($_POST['submit'])){
$to = "sample#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $name. " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
// echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
die();
}
?>
My Ajax 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();
});
});
Your code doesn't send any data to the server and will perform a GET request, so your if(isset($_POST['submit'])) will always return false when an AJAX request is made. You need to update your JavaScript so the form data is serialised:
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
method: 'post',
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();
});
});
You could improve your PHP too, by changing the if to something like this so it just detects the post request:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// ...
}

I am getting blank email from php and js

Please help me with decoding what the real issue is. The issue is that I keep getting a blank email, despite all my tweaking and research on this code. Below are my html, javascript (ajax) and php code.
HTML code: file named contact.html
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>
AJAX code:file named main.js
// Contact form
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">' + data.message + '</p>').delay(3000).fadeOut();
});
});
PHP code: file named sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
with this I keep on getting a blank email as depicted below
Name:
Email: Blank
Phone: Blank
Subject: Blank
Message: Blank
Have you tried with-out the die() at the end of your script? I think you might be killing your page too fast.
Also try creating a catch like this :
if (!mail(...))
{
// Reschedule for later try or panic appropriately!
}
Furthermore, you are suppressing warnings with # before mail();
Try removing the #.
Edit : Also, try removing the trims.
You have not set data while calling ajax, may be this is your problem.
When I test your code then I see that there fires a GET-request although you define the mehtod as POST in the form attribute. (Maybe that´s why jQuery use GET as default...). So the $_POST['name'] is empty because the parameter is in $_GET['name'].
And I can´t see the request parameters when I´m submiting the form. (Maybe that´s why the 'data' property is not set..)
Please try to complete the $.ajax with these:
method: 'POST'
data: $(this).serialize()
A BIG THANKS to ALL of you guys(#Mateusz Klimentowicz,#Mat VP,#Jose Manuel Abarca Rodríguez ,# Vladimir Nu). I actually followed your instructions and ended up correcting both the JS file and the PHP file as shown below:
JS file:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
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">' + data.message + '</p>').delay(3000).fadeOut();
});
});
While the PHP code became this below:
<?php
$status = array(
'type'=>'success',
'message'=>'Thank you for contacting us. As soon as possible we will contact you!'
);
$fail = array(
'type'=>'fail',
'message'=>'Please try again. Your mail could not be delivered!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#mail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
header('Content-type: application/json');
if($success){
echo json_encode($status);
}
else{
echo json_encode($fail);
}
?>
And after using this code as stated below, i end up not getting any blank page email. Email is now delievered with it's content. Thanks a bunch.

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!";
}
}
?>

PHP AJAX contact form dosen't send email

Trying to get an AJAX contact form to send the email but it dosen't work and, after throrough research, I still can't get what's wrong, so maybe one of you can help.
JS:
// Contact form
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();
});
});
PHP
<?php
if(isset($_POST['submit'],$_POST['name'],$_POST['email'],$_POST['message'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$email_from = $email;
$email_to = 'email#email.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
$response = array(); }
echo json_encode($response);
die;
?>
HTML
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" id="name" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" id="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
Please help! I'm out of options.
where is $subject initialised? I don't see it getting value in php code before sending it to the mail function
To send email you need to configure something like this, also you need to use
Less Secure Apps to be enabled (in case of Gmail). To enable Less Secure you
need to login to your account then click following link:
http://know.mailsbestfriend.com/smtp_error_password_command_failed_5345714-1194946499.shtml
public function sendEmail($email, $subject, $message) {
$config= array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'example#gmail.com',
'smtp_pass' => 'xxxxxxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->initialize($config);
$this->email->from('localhost', 'Team Name');
$this->email->to($email);
$this->email->subject($subject);
$this->email->message($message);
if(!$this->email->send()){
echo $this->email->print_debugger();
}
}
The data parameter is missing from you ajax function.
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: { // pass the data values sending through ajax
name : name,
email : email,
message : message
},
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();
});
});
You can obtain the values you want to send over through ajax to your php script as following:
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
Once you have obtained these values you can call the ajax function passing those as data parameters and setting the data type as POST. Then in your PHP script you can get the post values exactly as you did.

Categories