PHP form is sending blank email - php

I looked at other SO answers and I'm not getting an answer. I'm making a simple HTML form with an PHP script that sends an email. Simple. Except it's not working. Here's the HTML:
<form action="" method="post" id="contactform">
<fieldset>
<legend>Contact Form</legend>
<p><label>First Name: </label><input type="text" name="first_name" class="text" required></p>
<p><label>Last Name: </label><input type="text" name="last_name" class="text" required></p>
<p><label>Email: </label><input type="text" name="email" class="text" required></p>
<p><label>Message:</label><textarea rows="5" name="message" cols="30" class="message" required></textarea></p>
<input type="submit" name="submit" value="Submit" class="submit">
</fieldset>
</form>
Here's the AJAX:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#contactform").submit(function(){
$.get("contactsend.php", function(data){
alert(data);
})
return false;
})
</script>
And here's contactsend.php:
<?php
$to = "shubhang.desai#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From: " . $from;
if (mail($to,$subject,$message,$headers)) {
echo "Mail sent.";
} else {
echo "An error occured. Try again later.";
}
?>
When click submit, the page is saying "Mail sent.", but the email goes through blank. I'm not sure why array _POST would be empty. Could someone please help me out?
Thanks in advance :)

Your problem is you are not sent any data to server via ajax yet.
try with this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#contactform").submit(function(){
jQuery.ajax({
type: "POST",
url: "contactsend.php",
data: jQuery(this).serialize(),
success: function(data){
alert(data);
}
});
return false;
})
</script>
Php:
<?php
$to = "shubhang.desai#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: ' .$from. "\r\n";
if (mail($to,$subject,$message,$headers)) {
echo "Mail sent.";
} else {
echo "An error occured. Try again later.";
}

try:
$date = date( 'r' );
$phpversion = phpversion();
$headers = "From: ".$from."\nDate: ".$date."\nX-Mailer: PHP v".$phpversion."\nMIME-Version: 1.0\nContent-Type: text/html; charset=iso-8859-1\nContent-Transfer-Encoding: 8bit";

You've missed to send the values from the form to your server.
You can use .serialize() to get the values. It will transform them into a string with correctly encoded values.
$("#contactform").submit(function () {
$.get("contactsend.php", $(this).serialize(), function(data) {
alert(data);
});
return false;
});

You aren't sending any data along,try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#contactform").submit(function(){
var details = $(this).serialize();
$.get("contactsend.php",details, function(data){
alert(data);
})
return false;
})
</script>
The "serialize" function creates a query string automatically for a form,you can also serialize individual input fields.

Related

PHP email and url validation

So I've made myself a little contact form with php, css, and html. But when I try to add a email validation it still sends the email and doesn't change the style of the input to red (Like I would like it to). Another issue I'm having is the button redirecting to the top of the page (which I do not want it to do). Last I can I make the input keep the text rather than remove it once submitted
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" required>
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required>
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'mattmowen1#gmail.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
mail($to, $email_subject, $email_body,$headers);
} else {
echo "<style>#email-input {color:red}</style";
}
?>
Try this for email validation in php
<?php
if (isset($_POST) && !empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'mattmowen1#gmail.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
} else {
echo "<style>#email-input {color:red}</style>";
}
}
?>
As per our chat conversation. I am adding jquery ajax function according to your form requirement.
You need to create new file email.php and put your php code into this separate php file
<script>
var url = 'email.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) { // success
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else { // error
$('#email-input').css('color', 'red');//in case of email error
alert('ERROR MESSAGE');//form is invalid
}
}
})
</script>
To handle JSON request you need to send JSON object in response. So change you php code snippet like this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}

Mail function sending blank values

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).fade‌​Out();
},'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).fade‌​Out();
},'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).fade‌​Out();
},'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

Ajax + Jquery + PHP Mail Implementation Doesn't Send Mail [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 8 years ago.
I have a form which upon submission directs to a aspx page, which uses the form's data. Before directing to the above stated page, jquery is used alongside ajax to retrieve form values, and it sends everything to my php email file, which should be sending me informational emails whenever a form is submitted. Unfortunately I recevie nothing, everything else works, but I don't receive any email. Please help, I'm not sure why this isn't working.
Additional Info: I'm using wordpress and have called the jquery file via the functions.php. The php file is called via the jquery file.
Thanks in Advance!
HTML Form
<form action="https://redirection_page.aspx" method="get" name="nform" id="nform">
<div class="submission">
<div class="fname">
<input type="text" name="firstName" class="fname" placeholder="First name" required="">
</div>
<br>
<div class="lname">
<input type="text" name="lastName" class="lname" placeholder="Last name" required="">
</div>
<br>
<div class="email">
<input type="email" name="email" class="email" placeholder="example#email.com" required="">
</div>
<br>
<div class="phone">
<input type="text" name="homePhone" class="phone" placeholder="Phone Number" required="">
</div>
<br>
<br>
<!-- Edit the Continue Text -->
<div class="form-button">
<input type='button' class="submit tp-button green big :hover.green" value="Continue">
</div>
</div>
</form>
Jquery/Ajax
jQuery(document).ready(function($) {
var nform = $('#nform');
$('#nform .form-button input.submit').click(function(){
var data = {
first : $("#nform input.fname").val(),
last : $("#nform input.lname").val(),
email : $("#nform input.email").val(),
phone : $("#nform input.phone").val(),
};
$.ajax({
type: "POST",
url: "/wp-content/themes/Avada/email.php",
data: data,
success: function(){
$('#nform').submit();
}
});
});
});
PHP Mail
<?php
if($_POST){
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$sendto = "myemailaddress#gmail.com";
$message = "";
$message .= "<p> Name: " . $first . " " . $last "</p>";
$message .= "<p> Email: " . $email . "</p>";
$message .= "<p> Phone Number: " . $phone . "</p>";
$mail = 'no-reply#'.str_replace('www.', '', $_SERVER['SERVER_NAME']);
$uniqid = md5(uniqid(time()));
$headers = 'From: '.$mail."\r\n";
$headers .= 'Reply-to: '.$mail."\r\n";
$headers .= 'Return-Path: '.$mail."\r\n";
$headers .= 'Message-ID: <'.$uniqid.'#'.$_SERVER['SERVER_NAME'].">\r\n";
$headers .= 'Date: '.gmdate('D, d M Y H:i:s', time())."\r\n";
$headers .= 'X-Priority: 3'."\r\n";
$headers .= 'X-MSMail-Priority: Normal'."\r\n";
$headers .= 'Content-Type: multipart/mixed;boundary="----------'.$uniqid.'"'."\r\n";
$headers .= '------------'.$uniqid."\r\n";
$headers .= 'Content-transfer-encoding: 7bit';
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
//send email
mail($sendto, "Apply Submission by " .$email, $message, $headers);
}
?>
Try to make any feedback from mail.php, then success will fired:
...
//send email
mail($sendto, "Apply Submission by " .$email, $message, $headers);
header("Content-Type:text/html");
echo("ok");
}
?>
Try this:
$.ajax({
type: "POST",
async: false,
url: "/wp-content/themes/Avada/email.php",
data: data,
success: function(){
window.location = "https://redirection_page.aspx/"
}
});
PHP Mail
if(mail($sendto, "Apply Submission by " .$email, $message, $headers)){
echo 'true';
}

PHP mail() sends 2 copies

I have this problem with my contact form. When I submit the form I receive 2 identical emails in my box.
Im using JS to check the form for errors and then simple PHP mail() function to send the email.
Here is the PHP code:
<?php
$from = Trim(stripslashes($_POST['email']));
$to = "myemail#gmail.com";
$subject = "Contact Form";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$number = Trim(stripslashes($_POST['number']));
$message = Trim(stripslashes($_POST['message']));
$body = "";
$body .= "Name: ";
$body .= $name;
$body .= "\n\n";
$body .= "E-mail: ";
$body .= $email;
$body .= "\n\n";
$body .= "Telephone Number: ";
$body .= $number;
$body .= "\n\n";
$body .= "Message: ";
$body .= $message;
$body .= "\n\n";
$success = mail($to, $subject, $body, "From: <$from>" . "\r\n" . "Reply-to: <$from>" . "\r\n" . "Content-type: text; charset=utf-8");
?>
And here is the JS:
$(".submit").click(function() {
var name = $("input[name=name]").val();
var email = $("input[name=email]").val();
var number = $("input[name=number]").val();
var message = $("textarea[name=message]").val();
if (defaults['name'] == name || name == "") {
$(".error").text("Please enter your name!");
return false;
} else if (defaults['email'] == email || email == "") {
$(".error").text("Please enter your email!");
return false;
} else if (defaults['number'] == number || number == "") {
$(".error").text("Please enter your number!");
return false;
} else if (defaults['message'] == message || message == "") {
$(".error").text("Plese enter your message!");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&number=' + number + '&message=' + message;
$(".error").text("Please wait...").hide().fadeIn("fast");
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function() {
$('#form form').html("");
$('#form form').append("<div id='success'>Your message has been sent! Thank you</div>");
}
});
return false;
});
And here is the HTML form:
<form id="contact" method="post" action="#">
<label for="name">Name:</label>
<input type="text" name="name" required tabindex="1">
<label for="email">Email adress:</label>
<input type="text" name="email" required tabindex="2">
<label for="number">Tel. number:</label>
<input type="text" name="number" tabindex="3">
<label for="message">Your message:</label>
<textarea name="message" rows="10" cols="70" required tabindex="4"></textarea>
<input type="checkbox" id="terms" name="terms" value="terms">I agree to the terms
<input type="submit" name="submit" class="submit more-info" tabindex="5" value="Send">
<span class="error"></span>
</form>
I have been using the same code for all of my contact forms and it worked all right. Could it be hosting/server related issue?
replace your click event
$(".submit").click(function() {
with
$('.submit').unbind('click').click(function() {
code.
What I can assume your click event is binding two times may be due to a lot of the mess in the code
also use this line in the end of the click event function
$('.submit').unbind('click').click(function() {
// your stuff
event.stopImmediatePropagation(); // as long as not bubbling up the DOM is ok?
});
for reference have a look at the link: https://forum.jquery.com/topic/jquery-executes-twice-after-ajax
$(".submit").click(function(e) { ... }) POSTS to your server for the first time.
Because this is a <submit> button, the form will still submit. The form POSTS to your server for the second time.
The solution would be adding a e.preventDefault() at the bottom inside the $(".submit").click function...
$(".submit").click(function(e) {
// ^ add this e
var name = ...;
$.ajax({
...
});
e.preventDefault();
return false;
});
Try removing the jQuery animations:
$(".error").text("Please wait...").hide().fadeIn("fast");
They can sometimes cause problems.

Php form ajax "success & fail" message

The form on my website is a simple contact form.
I would like the form to show a "success & failed" message on the same page when the form is sent/failed without reloading the page. I understand that I should use Ajax to do this but I can't get it to work because my knowledge about it is very little.
Here is the code I'm working with.
Html (single page design):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">
<label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>
<input name="name" type="text" id="name" value="" />
<label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>
<input name="email" type="text" id="email" value="" />
<label for="phonetag">Telefon</label>
<input name="phone" type="text" id="phone" value="" />
<label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>
<textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>
<label class="placeholder"> </label>
<button class="submit" name="submit">Skicka</button>
</form>
<script>
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {alert(res);
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
</script>
Php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info#mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply#mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
Your Ajax call is not working properly. Try this
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
Also as you can see i have used $('#contactus').serialize() this way you dont need to pass the form elements one by one instead serialize() will pass the whole form elements to your php page
Than in your php file echo successful if everything went well else echo error if the response is an error than show the error div
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info#mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply#mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
Change your PHP script like this:
<?php
if( isset( $_POST['submit'] )){ //checking if form was submitted
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent="Meddelande: \n\n $message";
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$mailheader = "Från: $name \n Email: $email \n Telefon: $phone \r\n";
$mailsent = mail($recipient, $subject, $formcontent, $mailheader);
if($mailsent) echo "Success"; //success if mail was sent
else echo "Ett fel uppstod!";
}
?>
Below your mail() function, simply do echo "successful";
2020 Edit
In REST API response should be always accompanied by the correct HTTP status code, with 200+ telling client that request ended up correctly processed or was otherwise good, 400+ telling client there was an error in request, and 500+ that there was a problem with the server itself. Do not use statuses inside responses, it is unnecessary duplication of the existing feature:
http_response_code(200);
echo json_encode(['message' => 'Email was sent']);
exit;
Then you can handle request and response with jQuery(assuming that you still use jQuery):
$.ajax({
url: url,
data: data,
dataType: 'json'
})
.then(function (data, textStatus, jqXHR) {
// Your 200+ responses will land here
})
.fail(function (jqXHR, textStatus, errorThrown) {
// Your 400+ responses will be caught by this handler
});
;
If you need specific status, you can get it from jqXHR parameter using jqXHR.status field.
Original answer
You can use dataType: 'json' in your ajax call.
Then you'll be able to pass status code as response key:
// form response array, consider it was success
$response = array( 'success'=> 'ok', 'message' => 'Email was sent');
echo json_encode($response);
In js then you can check data.success === 'ok' to know what's your status.
In your php script you could try this
if(mail($recipient, $subject, $formcontent, $mailheaders))
{
echo("Mail Sent Successfully"); // or echo(successful) in your case
}else{
echo("Mail Not Sent"); // or die("Ett fel uppstod!");
}

Categories