I am trying to send an email to user account using php mail() function.The mail is sent successfully but the issue is that it is sending me blank emails with no values in them! The code for the contact page that sends the email is as follows:-
<form class="contact-form" method="POST" action="sendemail.php">
<div class="row-fluid">
<div class="span5">
<label>First Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your First Name" name="name">
<label>Last Name</label>
<input type="text" class="input-block-level" required="required" placeholder="Your Last Name" name="lname">
<label>Email Address</label>
<input type="text" class="input-block-level" required="required" placeholder="Your email address" name="email">
</div>
<div class="span7">
<label>Message</label>
<textarea name="message" id="message" required="required" class="input-block-level" rows="8" name="message"></textarea>
</div>
</div>
<input type="submit" class="btn btn-primary btn-large pull-right" value="Send Message" />
<p> </p>
</form>
and sendemail.php page code is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = "An enquiry sir";
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';
echo $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;
?>
Why is the output I get blank in my email id, for example:
Name:
Email:
Subject:
Message:
P.N: I am using here a nova template theme.
The form is being submitted via AJAX using the following JavaScript:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
the form submission code is not submitting the form data. Here is the code you provided:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
and this is what it should be:
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
Remove the echo from the line that defines $body
From this...
echo $body = 'Name: ' . $name . "\n\n" . 'Email
To this...
$body = 'Name: ' . $name . "\n\n" . 'Email
Related
I'm using g-Recaptcha v3 to pass a hidden token and HTML "Contact" form data to form.php file on the localhost, which verifies the g-Recaptcha data, returns a default prompt to end-user and sends an email, via the localhost to the default email address.
The email received does not display data captured, via the HTML "Contact" form. I have tried changing the syntax, I have tried additional "If/Else" statements as well as adding "POST" commands without any success.
HTML contact form section:
<!-- The Contact Section -->
<div class="w3-container w3-content w3-center w3-blue-gray w3-padding-64" style="max-width:1400px" id="contact">
<div class=" w3-container w3-content w3-center" style="max-width:1000px">
<h2 class="w3-wide">Contact</h2>
<p class="w3-opacity"><i>~ Lets Talk About Your Current Needs ~</i></p>
<form id="comment_form" action="form.php " method="post" target="_blank" >
<input class="w3-input w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your First Name: ex. Mark (with no spaces, punctuations or symbols)" name="fname" maxlength="32" pattern="[A-Za-z]{1,32}" required><br>
<input class="w3-input w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your Last Name: ex. Wilson (with no spaces, punctuations or symbols)" name="lname" maxlength="32" pattern="[A-Za-z]{1,32}" required>
<input class="w3-input w3-section w3-border w3-text-gray w3-center" type="text" placeholder="Enter Your Email: ex. yourname#domainname.com" name="email" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$" required>
<input class="w3-input w3-section w3-border w3-text-gray w3-center" placeholder="Enter Your Phone Number: ex.(112)112-1112 or 1121121112" name="phone" pattern="^(\s*)?(\+)?([- _():=+]?\d[- _():=+]?){10,14}(\s*)?$" required>
<textarea class="w3-input w3-section w3-border w3-text-gray w3-center" placeholder="Please Place Your Comment Here" name="comment" rows="5" required></textarea>
<i class="fa fa-paper-plane-o"></i>
<input type="submit" name="submit" value="SEND MESSAGE" class="w3-text-black"><br><br>
</form>
<script>
// when form is submit
$('#comment_form').submit(function() {
// we stopped it
event.preventDefault();
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var phone = $('#phone').val();
var comment = $("#comment").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('----------My Public Key----------', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{fname: fname, lname: lname, email: email, phone: phone, comment: comment, token: token}, function(result) {
console.log(result);
if(result.success) {
alert('Thanks for posting your comment!')
} else {
alert('Spammed Message - This Process Will Be Terminated')
}
});
});;
});
});
</script>
form.php
<?php
$fname;$lname;$email;$phone;$comment;$captcha;
if(isset($_POST['fname'])){
$fname=$_POST['fname'];
}if(isset($_POST['lname'])){
$lname=$_POST['lname'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['phone'])){
$phone=$_POST['phone'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "--------------My Secret Key-----------------";
$ip = $_SERVER['REMOTE_ADDR'];
// POST REQUEST TO SERVER
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
header('Content-type: application/json');
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
} else {
echo json_encode(array('success' => 'false'));
}
// COLLECT CONTACT FORM DATA
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$number = $_POST['phone'];
$comment = $_POST['comment'];
// FORMAT EMAIL
$to = "default#emailaddress.com";
$headers = "From: {$to} \r\n";
$headers .= "Reply-To: {$email } \r\n";
$subject = "New form submission ... \r\n";
$body = "First Name: {$fname} \r\n";
$body .= "Last Name: {$lname} \r\n";
$body .= "Email: {$email} \r\n";
$body .= "Phone: {$phone } \r\n";
$body .= "Comment: {$comment}";
// SEND EMAIL to DEFAULT RECIPIENT VIA LOCALHOST
$send = mail($to, $subject, $body, $headers);
?>
HTML contact form:
Google g-recaptcha v3 verification prompt:
Email, via contact form, with missing data:
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.
Email is arriving at the destination address but with blank fields. What is the cause?
My use of mail() is as follows:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$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 = 'info#siteaddress.com';
$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;
?>
And the form HTML is:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" class="form-control" required placeholder="Name" name="name" id="name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="text" class="form-control" required placeholder="Email address" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message" name="message" id="message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</div>
</div>
</form>
$subject = #trim(stripslashes($_POST['subject'])); but your form don't have subject, you should add it.
Don't suppress errors by #, because you never will know what exactly happens with your code.
Finally Got the Answer.... Problem is that my form was not posting anything because the following script was missing
<script>
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'),$(this).serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
</script>
i have added $(this).serialize() to the script and now the mail is working properly...
Thanks all of you....
Hi I´m have the same problem on a 000webhost app. I solve this with two moodifications
1rst:
Add var name = $("input#name").val(); for a form values and in to the ajax function name: name, for a form values
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: {
name: name,
email: email,
subject: subject,
message: message,
},
cache: false,
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email enviandose</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success"> Gracias por la consulta, a la brevedad estaremos respondiendo</p>').delay(3000).fadeOut();
//clear all fields
$('#main-contact-form').trigger("reset");
});
});
2nd: The tag id"name" id"email" id"XX" in mi Form in my case
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
//to Replace This
$header .= 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>',,$header);
if( $success == true )
{
//success Message
}
else{
//Error Message
}
Very new to this so apologies is my question is basic but it's stumped me for some hours.
I have a contact form which uses a bit of AJAX to POST to my PHP file. The problem im having is that when i try to get the PHP to email that data to myself, it isn't reading the POST values. The PHP was working when i tested it without the JS/AJAX post method, but in order to stop the page refresh I have gone with the AJAX option. Now that i've added the ajax in, the email result isn't showing up with the data (I can inspect and see that the Form Data is filled, just unclear why it isnt populating in the email) :
Name:
Email:
Message:
Any guidance as to why my mail server only receives the text but not the POST
Opening & Closing HTML on form:
<form data-parsley-validate action="./assets/contactform.php" method="POST">
<div class="formRow">
<label for="name" class="obscure">Name</label>
<input type="text" name="nameInput" id="name" placeholder="Name" required data-parsley-error-message="Please enter your name"></input>
</div>
<div class="formRow">
<label for="email" class="obscure">Email</label>
<input name="emailInput" id="email" type="email" placeholder="Email" required data-parsley-error-message="Please enter a valid email address"></input>
</div>
<div class="formRow">
<label for="message" class="obscure">Message</label>
<textarea name="messageInput" id="message">Message</textarea>
</div>
<input type="submit" name="submit"></input>
PHP Script:
<?php
$to = 'hello#kymlangford.com';
$subject = 'Post from your website';
$message = "Name: " . $_POST['nameInput'] . "\n Email: " . $_POST['emailInput'] . "\n Message: " . $_POST['messageInput'];
$headers = 'From: hello#kymlangford.com' . "\r\n" .
'Reply-To: ' . $_POST['emailInput'] . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
exit;
?>
Java for the form:
$(function() {
$.ajax({
type: 'POST',
url: './assets/contactform.php',
data: { name : $('input[name=nameInput]').val(),
email : $('input[name=emailInput]').val(),
message : $('textarea[name=messageInput]').val()
},
dataType: 'json'
})
event.preventDefault();
});
});
--Update 08/07/2014--
Below is the jquery code that solved my problem
// get the data from the form
$('form').submit(function(event){
var fdata = $(this).serializeArray();
fdata.push({ name: 'submit', value: true });
$.post('./assets/contactform.php', fdata, function (data) {
alert('Data Loaded:' + data); });
console.log(fdata);
event.preventDefault();
});
});
I think you can use jquery which is the same like ajax.
Here is the HTML code
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("sendemail.php", $("#contactform").serialize(), function(response)
{
$('#message').html(response);
});
return false;
});
});
</script>
</head>
<body>
<p>
<form action="" method="post" id="contactform" >
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="emailcontent">Email Content:</label><br />
<textarea name="emailcontent" id="emailcontent"></textarea><br />
<input type="button" value="Send Email" id="submit" /><div id="message"> </div>
</form>
</p>
</body>
</html>
Here is the PHP code, save it with 'sendemail.php' filename
$name = $_POST['name'];
$email = $_POST['email'];
$emailcontent = $_POST['emailcontent'];
$to = 'youremail#domain.com';
$subject = 'the subject';
$emailcontent = 'FROM: '.$name.' Email: '.$email.'Content: '.$emailcontent;
$headers = 'From: youremail#domain.com' . "\r\n";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
I have been having ongoing issues with this contact form. I am now trying to get the mobile number part to work.
I have been able to get it to work with someone code from here but it loses the format that I would like to keep. Can anyone find a reason why this form is not sending the mobile number?
site: www.krjwoodcraft.com
send.php
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$message= $_POST['message'];
$mobile = $_POST['mobile'];
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
contact.js
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var mobile = $("#mobile").val();
var error = false;
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}else{
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(name.length == 0){
var error = true;
$("#error_name").fadeIn(500);
}else{
$("#error_name").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "You Got Email" + "&message=" + message + "&mobile=" + mobile,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
html:
<!-- Contact Form -->
<div class="row">
<div class="span12">
<div class="trac_contactform">
<form id="contact_form" class="row" name="form1" method="post" action="send.php">
<div class="span6">
<input type="text" class="full" name="name" id="name" placeholder="Name" />
<div id="error_name" class="error">Please check your name</div>
</div>
<div class="span6">
<input type="text" class="full" name="email" id="email" placeholder="Email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span6">
<input type="text" class="full" name="mobile" id="mobile" placeholder="Phone Number"/>
</div>
<div class="span6">
<input type="text" class="full" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="span12">
<textarea cols="10" rows="10" name="message" id="message" class="full" placeholder="Message"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send Now" class="btn btn-large btn-primary btn-embossed" /></p>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!--END CONTACT PAGE-->
As Hanky 웃 Panky correctly pointed out you are not including the phone number to your email message. Try the following code. I stored the $_POST['message'] in a new variable called $sent_message and modified your $message variable to include the $subject, $sent_message and the $mobile variables.
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$sent_message = $_POST['message'];
$mobile = $_POST['mobile'];
$message = "Subject: " . $subject . "\r\n" . "Message: " . $sent_message . "\r\n" . "Phone number: " . $mobile;
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
You did not include it in your mail body. you have passed mobile number in php file. You got the file but you don't use it in your mail body.
include mobile number :
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message."\r\n" . "Phone number: " . $mobile), $header);