This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I'm using a php mail script from http://blog.teamtreehouse.com/create-ajax-contact-form connected to a contact form on a website I'm building.
I have everything put together and it seems to function properly (doesn't display any errors), but I am not receiving most of the emails. If I test the contact form using one of my personal email accounts I will receive the message. If I use any other emails (for example something from http://www.fakemailgenerator.com) I won't receive anything. I've attached all of the code below. Is there something I'm missing that anyone can spot?
If it helps, the site is hosted in an AWS LAMP linux instance and the domain is with GoDaddy.
Thanks in advance.
contact.html
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<input type="text" id="name" name="name" placeholder="name*" required>
</div>
<div class="field">
<input type="email" id="email" name="email" placeholder="email*" required>
</div>
<div class="field">
<input type="text" id="school" name="school" placeholder="school" >
</div>
<div class="field">
<input type="tel" id="phone" name="phone" placeholder="phone" >
</div>
<div class="field">
<textarea id="message" name="message" placeholder="message" ></textarea>
</div>
<div class="field">
<button type="submit">Submit</button>
</div>
</form>
mailer.php
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$school = trim($_POST["school"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "There was a problem with your submission. Please ensure all required fields are filled out.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "sample#gmail.com";
// Set the email subject.
$subject = "Sample subject - New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "School: $school\n";
$email_content .= "Phone: $phone\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent. We'll get back to you as soon as possible.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message. Please try again later.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
app.js
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#phone').val('');
$('#school').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
I think it's simply Amazon that filter suspicious mail provider. Most of SMTP server comes with filters. Thoses filters prevents user to receive spam.
As said from Amazon FAQ :
Amazon SES uses in-house anti-spam/anti-virus technologies to filter email messages containing poor-quality content and prevent them from being sent.
Your message formatting is just wrong, I'm not going to begin to correct it. Use a library to do it right - you already tagged this question with PHPMailer, but you're not using it. Base your code on one of the examples provided with PHPMailer, not one you find elsewhere as nearly all are obsolete or wrong.
You're also forging the from address, so many services will just reject or bounce your messages. Send from your own address and put the submitter's address in reply-to.
Also ensure that your SPF record is configured correctly, and ideally sign your messages with DKIM too.
Related
This might be a lot of code I am sorry in advance. I am leaving work right now so I might not reply right away if someone has a solution or can run this locally and help me that would be great.
I've never done one of these form submissions with the backend PHP before (I'm usually just front end). I am getting this 400 bad request error that I'm not real sure what to do. I put the PHP separate from the snippet since there's no spot that I can see in the snippet to play PHP code.
My directory structure is this:
public(root):
-(inside public) assets/js/mailer.js
-(inside public) mailer.php
$(document).ready(function() {
$("#submit").on('click', function() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var institution = $('#institution').val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || phone == '' || institution == '' || message == '') {
alert("Please Fill Required Fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("../../mailer.php", {
name1: name,
email1: email,
institution1: institution,
contact1: phone,
message1: message
},
function(data) {
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Your message was received. We will contact you shortly.") {
$("#ajax-contact")[0].reset(); // To reset form fields on success.
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="row">
<div class="col-lg-6 input-field-name form-group">
<input type="text" class="form-control scroll-left" placeholder="Name" id="name" name="name" required>
</div>
<div class="col-lg-6 input-field-email form-group">
<input type="text" class="form-control scroll-right" placeholder="Email" id="email" name="email" required>
</div>
</div>
<div class="form-group">
<input type="tel" class="form-control scroll-bottom" placeholder="Phone" id="phone" name="phone" required>
</div>
<div class="form-group">
<input type="text" class="form-control scroll-bottom" placeholder="Institution / Organization" id="institution" name="institution" required>
</div>
<div class="form-group">
<textarea class="form-control scroll-bottom" placeholder="Message" id="message" name="message" required></textarea>
</div>
<p id="returnmessage"></p>
<input type="button" id="submit" class="submit scroll-top"><span>Submit</span></input>
</form>
Here its the PHP:
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$institution = trim($_POST["institution"]);
$phone = trim($_POST["phone"]);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// $cont_subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$required = "This field is required";
// Check that data was sent to the mailer.
if ( empty($name) OR empty($institution) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo $required;
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "example#example.com";
// Set the email subject.
$subject = "New message from: $name ($email)";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Institution: $institution\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Message:\n$message";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
echo "Thank You! Your message has been sent.";
} else {
echo "Something went wrong and we couldn't send your message.";
}
}
else {
echo "There was a problem with your submission, please try again.";
}
?>
I tested your code - see below. There where some problems with it, which I describe in detail in the comments. Just search for #todo, #see and #link.
I deliberately emptied the variable $recipient and commented the mail sending part at the end of "mailer.php". So, fill in the $recipient's value and uncomment the mail sending part, in order to test.
I tried to change just the essential code parts.
P.S: The headers topic is not quite an easy one at first sight. So feel free to ask me anything and I'll do my best to explain it to you on the SO chat.
public/index.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<!-- CSS assets -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/mailer.css">
<!-- JS assets -->
<!-- #todo Loaded needed js resources and mailer.js -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="assets/js/mailer.js"></script>
</head>
<body>
<!-- #todo Added container. -->
<div class="container">
<!-- #todo Added header. -->
<header>
<h2>
Demo
</h2>
</header>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="row">
<div class="col-lg-6 input-field-name form-group">
<input type="text" class="form-control scroll-left" placeholder="Name" id="name" name="name" required>
</div>
<div class="col-lg-6 input-field-email form-group">
<input type="text" class="form-control scroll-right" placeholder="Email" id="email" name="email" required>
</div>
</div>
<div class="form-group">
<input type="tel" class="form-control scroll-bottom" placeholder="Phone" id="phone" name="phone" required>
</div>
<div class="form-group">
<input type="text" class="form-control scroll-bottom" placeholder="Institution / Organization" id="institution" name="institution" required>
</div>
<div class="form-group">
<textarea class="form-control scroll-bottom" placeholder="Message" id="message" name="message" required></textarea>
</div>
<p id="returnmessage"></p>
<!-- #todo Changed button bec. the "input" code was wrong - it didn't fire the onclick event. -->
<button type="button" id="submit" class="btn btn-success">
<span>Submit</span>
</button>
</form>
</div>
</body>
</html>
public/assets/js/mailer.js:
$(document).ready(function () {
$("#submit").on('click', function () {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var institution = $('#institution').val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || phone == '' || institution == '' || message == '') {
alert("Please Fill Required Fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
/*
* #todo Changed the path to "mailer.php" because the path must be relative
* to the including page (here "index.php"), not to the included file (here "mailer.js").
* #todo Changed "name1" to "name", etc, because see mailer.php #todos.
* #todo Added the "fail" callback. Why? Because:
* The page "mailer.php" throws a 420 (earlier 400) response header (from the "if" statement),
* which is read by the browser and, based on its code (420), recognized as an error. So,
* the browser activates the "fail" callback.
* From the jQuery website: "If a request with jQuery.post() returns an error code,
* it will fail silently". So you must define a "fail" callback to handle the eventual errors.
*
* Note that, if the status code of the response is a custom one (420), defined by
* the developer, then the corresponding error message is to be displayed.
* Otherwise, e.g. if a system error occurres, the displayed message must
* be a general, user-friendly one. So that no system-related infos will be shown to any user!
*
* Try to toggle between 420 and 400 in "mailer.php", in order to
* see which error message is displayed in the "fail" callback.
*
* #link https://api.jquery.com/jQuery.post/ jQuery.post().
* #link https://api.jquery.com/jQuery.ajax/ jQuery.ajax().
*/
$.post("mailer.php", {
name: name,
email: email,
institution: institution,
contact: phone,
message: message
}, function (data) {
//#todo Added this line. It adds a "success" class to the "returnmessage" container.
$("#returnmessage").removeClass('error').addClass('success');
$("#returnmessage").append(data); // Append returned message to message paragraph.
$("#ajax-contact")[0].reset(); // To reset form fields on success.
}).fail(function (jqXHR, textStatus, errorThrown) {
var message;
if (jqXHR.status === 420) {
// The status code of the response is a custom one (420).
message = jqXHR.statusText;
} else {
/*
* A system error occurred. E.g. the status code of the response is set by
* the system. For example a 400 code (described with the text "Bad Request").
*/
message = 'An error occurred during your request. Please try again, or contact us.';
}
//#todo Added this line. It adds an "error" class to the "returnmessage" container.
$("#returnmessage").removeClass('success').addClass('error');
$("#returnmessage").append(message);
});
}
});
});
public/assets/css/mailer.css:
#returnmessage.error {
color: #c00;
}
#returnmessage.success {
color: #3adb76;
}
public/mailer.php:
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/*
* #todo This part activated a "400 bad Request" error because, for example,
* you've sent "name1" from ajax, but here you are referencing the "name".
* #see The comment marked with [*] bellow.
*/
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r", "\n"), array(" ", " "), $name);
$institution = trim($_POST["institution"]);
//#todo Changed from "phone" to "contact", because "contact" were posted, not "phone".
$phone = trim($_POST["contact"]);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// $cont_subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
/*
* #todo Try to use the logical operator "||" instead of "OR", "&&" instead of "AND", etc.
* #link https://secure.php.net/manual/en/language.operators.logical.php Logical Operators.
*/
if (
empty($name) ||
empty($institution) ||
empty($phone) ||
empty($message) ||
!filter_var($email, FILTER_VALIDATE_EMAIL)
) {
/*
* #todo
*
* [*] This code triggered the 400 header because
* the values posted by ajax were undefined.
*
* I changed to "header(...)" instead of "http_response_code(...)" + "echo ...".
*
* I changed 400 to 420 because 400 is a code
* reserved by the system. See the rule bellow:
*
* This custom response header triggers the ajax error (see the "fail" callback in the js file)
* because the status code begins with 4xx (which corresponds to the "client errors"). Here is
* defined "420" as the custom status code. One can choose whatever code between 401-499 which
* is not officially assigned, e.g. which is marked as "Unassigned" in the official
* HTTP Status Code Registry. See the link.
*
* #link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
// Send a 420 custom response header (to the browser) and exit.
header('HTTP/1.1 420 This field is required');
exit();
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
/*
* #todo Don't post sensible info on public websites!
* I deleted the email address. Fill it on your system.
*/
$recipient = "";
// Set the email subject.
$subject = "New message from: $name ($email)";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Institution: $institution\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Message:\n$message";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
//#todo Uncomment only after assigning an email address to the "$recipient" variable.
// $mailSent = mail($recipient, $subject, $email_content, $email_headers);
/*
* #todo You can toggle between TRUE and FALSE to test, then delete
* this line after activating the line "$mailSent = ..." above.
*/
$mailSent = TRUE;
if ($mailSent) {
echo "Thank You! Your message has been sent.";
} else {
/*
* #todo Here too: Throw a custom response header instead of just printing a text.
* This way the header will be treated as error by the browser, which will manage
* it with the "fail" callback of the ajax request.
*/
// Send a 420 custom response header (to the browser) and exit.
header('HTTP/1.1 420 Something went wrong and we could not send your message.');
exit();
}
} else {
/*
* #todo Here too: Throw a custom response header instead of just printing a text.
* This way the header will be treated as error by the browser, which will manage
* it with the "fail" callback of the ajax request.
*/
// Send a 420 custom response header (to the browser) and exit.
header('HTTP/1.1 420 There was a problem with your submission. Please try again.');
exit();
}
I'm trying to add Google's invisible recaptcha in my website. It is basically for a contact us form where the user submits his name, email and message and on clicking submit will trigger a mail to us.
I planned to take care of the mail part using php. However, I am not able to get past submitting the form in jquery.
This is my html :
<div class="row">
<script src="mail.js"></script>
<form id="main-contact-form" name="contact-form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Name" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control" rows="2" placeholder="Message" required></textarea>
</div>
<button class="g-recaptcha btn btn-primary" data-sitekey="6LdGAiQUAAAAAHeNXI3yDSsZhLAJs7U1HX_zXm8o" data-callback="onSubmit" type="submit">Submit</button>
</form>
</div>
The onSubmit callback:
function onSubmit(response) {
var request;
console.log('here');
document.getElementById('main-contact-form').submit();
}
The jQuery code for passing the submitted form to the php where verification of the captcha is done mail is sent:
$("#main-contact-form").submit(function(event) {
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
console.log('in here');
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function(response, textStatus, jqXHR) {
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function(jqXHR, textStatus, errorThrown) {
// Log the error to the console
console.error(
"The following error occurred: " +
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function() {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
Php code for mailing:
<?php
$name;$email;$message;$captcha;
if(isset($_POST['name'])){
$name=$_POST['name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
exit;
}
$secretKey = "secret key";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha.);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>Message could not be sent</h2>';
} else {
$name = #trim(stripslashes($name));
$from = #trim(stripslashes($email));
$subject = #trim(stripslashes('contact'));
$message = #trim(stripslashes($message));
$to = 'email#email.com';//replace with your email
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();
mail($to, $subject, $message, $headers);
echo '<h2>Thanks for posting comment.</h2>';
}
?>
?>
The PHP code might not be correct and I am yet to work on that (I haven't used PHP before.).
Now, when I try to submit the form, the page reloads with the form as query params in the address bar. Even, when event.preventDefault() is given for when the form is submitted in the onSubmit callback of Recaptcha, it reloads the page.
Please help me with getting this working. Also I do not want to refresh the page when the form is submitted as I plan to use ajax for sending the form input to the php script.
I have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".
I want to submit the form with the captcha and alert the user with a success note without refreshing the page.
I tried the following code, but it seems like the server doesn't get the user response:
HTML:
<form class="form" action="javascript:void(0)" novalidate>
<!-- all the inputs... -->
<!-- captcha -->
<div class="input-group">
<div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
</div>
<div class="errors" id="errors" style="display: none"></div>
<div class="input-group">
<input type="button" value="Send" class="btn-default right" id="submit">
<div class="clear"></div>
</div>
</form>
JS:
$('#submit').click(function(e) {
console.log('clicked submit'); // --> works
var $errors = $('#errors'),
$status = $('#status'),
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
valid = false;
errors = "All fields are required.";
}
// pretty sure the problem is here
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
if (!errors) {
// hide the errors
$errors.slideUp();
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "http://orenurbach.com/assets/sendmail.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// slide down the "ok" message to the user
$status.text('Thanks! Your message has been sent, and I will contact you soon.');
$status.slideDown();
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
} else {
$errors.text(errors);
$errors.slideDown();
}
});
PHP:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = '';
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
echo 'captcha: '.$captcha;
if (!$captcha)
echo 'The captcha has not been checked.';
// handling the captcha and checking if it's ok
$secret = 'MY_SECRET';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
var_dump($response);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response['success'] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo 'ok';
} else {
echo 'not ok';
}
?>
The result in the PHP page:
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok
Bottom line is, how can I get the input response manually without it automatically going with the rest of the POST data?
Ok, this was pretty silly.
I have done a couple of things wrong:
In the PHP file, all the strings had single quotes on them, and that caused problems.
Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok") was never working. I did get the emails but did not get any conformation that I did and now I see why.
When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.
Thanks to #Samurai who helped my figure out things.
Final PHP code:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
if (!$captcha)
echo "not ok";
// handling the captcha and checking if it's ok
$secret = "MY_SECRET";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response["success"] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo "ok";
} else {
echo "not ok";
}
?>
In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/
I have this html markup:
<form id="ajax-contact" method="post" action="mailer.php">
<div id="form-messages"></div>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" class="contact" name="name" placeholder="Name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" class="contact" name="email" placeholder="Email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
this jQuery (for the AJAX call):
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
and this mailer.php file:
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "email#email.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
The issue is that after I press the submit button, I receive this message:
Oops! An error occured and your message could not be sent.
When I check the console I see this error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) which is the mailer.php file.
However, when I check my inbox I see the email submitted in the form.
I can not figure out what is going wrong, can someone tell how can I fix this issue?
Thank you!
You are using the wrong error number - 500 is reserved for faults in code (hence why internal server error).
Even for security reasons, always send 200 however when mail returns false, log the email in a text file. Together with the get_last_error function, so that you can properly analyze your issue.
Hope this helps.
http://www.w3schools.com/php/func_error_get_last.asp