I'm kind of new to this. I have been working around this from someone a while about sending a mail from an HTML form to my inbox and want to display the filled inputs in my inbox with other messages to display in the inbox.
index.html
<form action="mail.php" method="post">
<section id="left">
<label for="form_name">Name</label>
<input name="form_name" id="form_name" type="text" >
<label for="form_email">Email</label>
<input name="form_email" id="form_email" type="email" >
<label for="form_msg">Message</label>
<textarea name="form_msg" id="form_msg"></textarea>
<input id="submit" class="button" name="submit" type="submit" value="send">
</section>
</form>
mail.php
<?php
if($_POST){
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
$phone = $_POST['phone_no'];
//send email
mail("myemail#gmail.com", "This is a Reservation from:" ,Name. ':' . $name, $email, $phone);
}
?>
mail.js
$.ajax({
type: "POST",
url: "email.php",
data: $(form).serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
mail("kondasmajid#gmail.com", "This is a Reservation from:" ,Name. ':' . $name, $email, $phone);
...that line won't lead nowhere. In PHP, you have to concatenate strings through a dot, so the following line should work:
mail("kondasmajid#gmail.com",
"This is a Reservation from: Name:" . $name . ", Email: " . $email . ", Phone: " . $phone);
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:
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
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.
Sounds like an odd question but here is what I have. The php has a snippet at the end that says success or failure makes a white screen to display this, I really want it to pop up right under the submit button on the same page rather than redirect the entire page.
I assume I could direct that to an empty <div>?
mail.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "art#jamisonsigns.com";
$subject = "Web Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
With a simple HTML form on my website as follows:
<form class="contact-form" form action="mail.php" method="POST">
<fieldset>
<input type="text" class="name" id="name" placeholder="Name...">
</fieldset>
<fieldset>
<input type="email" class="email" id="email" placeholder="Email...">
</fieldset>
<fieldset>
<input type="text" class="phone" id="phone" placeholder="Phone...">
</fieldset>
<fieldset>
<textarea name="message" id="message" cols="30" rows="4" placeholder="Message.."></textarea>
</fieldset>
<fieldset>
<input type="submit" class="button" id="button" value="Send Message">
</fieldset>
</form>
You need to submit the form with Ajax. Then on success insert the message in the html.
$('#button').click(function(event) {
event.preventDefault();
var formdata = $('#formID').serializeArray();
var url = '/urltopost.php';
$.ajax(
{
url : url,
type: "POST",
data: formdata,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
console.log("STATUS:" + textStatus + " | jqXHR:" + jqXHR + " | data:" + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR:" + " -> " +errorThrown);
}
});
});
Here it is a tutorial if you need..
I'm having a hard time with this reCAPTCHA integration.
Here's my code so far:
HTML
<div class="form_contact">
<form id="form1" name="form1" method="post" action="#">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" placeholder="*Required Field" />
</div>
<div>
<label for="name">E-mail address:</label>
<input type="email" name="email" id="email" value="" tabindex="2" placeholder="*Required Field" />
</div>
<div>
<label for="name">Message Subject:</label>
<input type="text" name="msgTitle" id="msgTitle" value="" tabindex="3" placeholder="*Required Field" />
</div>
<div>
<label for="textarea">Message:</label>
<textarea cols="40" rows="8" name="message" id="message" tabindex="4" placeholder="*Required Field"></textarea>
</div>
<div>
<label for="textarea">Spam Blocker:</label>
<div class="captcha">
<?php
require_once('recaptchalib.php');
$publickey = "**********************************";
echo recaptcha_get_html($publickey);
?>
</div>
<a class="myButton" tabindex="5" id="submit" name="submit" href="#"> Submit <i class="fa fa-chevron-circle-right fa-2x"></i></
</form>
</div>
JQuery
<script>
$(function(){
$('.myButton').click(function() {
var data= {
name: $("#name").val(),
email: $("#email").val(),
msgTitle: $("#msgTitle").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(data){
console.log(data);
}
});
alert('Message Sent!');
return false;
});
});
</script>
MAIL.php
<?php
require_once('recaptchalib.php');
$privatekey = "*******************";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
$mailto = 'sample#example.com';
$nameField = $_POST['name'];
$emailField = $_POST['email'];
$emailSubject = $_POST['msgTitle'];
$messageField = $_POST['message'];
$body = <<<EOD
<br><hr><br>
Name: $nameField <br>
Email: $emailField <br>
Message: $messageField <br>
EOD;
$headers = "From: $emailField\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
echo 'message sent!';
}
?>
I just want to display the error message below of the <form> if the reCAPTCHA inputs are incorrect.
Thanks in advance.!
Looks like a jQuery question, you can create a placeholder below the form to push in all the errors:
</form>
<div id="errors"></div>
And in your AJAX success call do:
success: function(data){
//clean it in case of multiple attempts
$('#errors').html(data);
}
.html() pastes the data sent from the server.
From the answer above I just wanna add this code if you want to return a callback from your backend
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
then you may want to change die into echo like so:
echo "The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"reCAPTCHA said: " . $resp->error . "";
then it should be like:
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(data){
$('#errors').html(data)
}
});