Php mail being sent from simple POST request but not when using AJAX - javascript

So I have a website with a simple contact form and I would like to receive the message by email.
I created my mail.php handler :
<?php
$owner_email = "somebody#somemail.com";
$headers = 'From:' . $_POST["email"];
$subject = 'A message from your site visitor ' . $_POST["name"];
$messageBody = "";
// some verifications
try{
if(!mail($owner_email, $subject, $messageBody, $headers)){
throw new Exception('mail failed');
}
else{
echo 'mail sent';
}
}
catch(Exception $e){
echo $e->getMessage() ."\n";
}
?>
If I create a simple HTML form like this :
<form method="post" action="mail.php">
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="submit" name="submit" type="submit" value="Submit">
</form>
everything works fine and I receive the email in my mailbox.
If I send a POST request from my browser at http://mywebsite.com/mail.php the answer is "mail sent" and I receive the email in my mailbox.
However when I want to use some JavaScript to dynamically validate the form fields and then send the POST request by using Ajax I don't receive anything. Here is my JavaScript :
mailHandlerURL:'mail.php',
...
// on submit when all validations are OK
$.ajax({
type: "POST",
url:_.mailHandlerURL,
data:{
name:_.getValFromLabel($('.name',_.form)),
email:_.getValFromLabel($('.email',_.form)),
phone:_.getValFromLabel($('.phone',_.form)),
message:_.getValFromLabel($('.message',_.form)),
stripHTML:_.stripHTML
},
success: function(response){
console.log(response);
_.showFu(); // to display to the user that the email has been sent
}
})
console.log() shows : "mail sent" so the mail.php is called correctly.
The application is hosted on OpenShift and uses PHP 5.4

Related

Receiving PHP contact form error (Please complete the form and try again. )

I am creating a contact form with 5 fields which will email the input details to a set e-mail but when the form is submitted i,m receiving error! Please complete the form and try again. here is php code, js and htm form.
Any help would be much appreciated.
html Form:
<form id="contact-form" action="mail.php" method="post">
<div class="single-input">
<input type="text" name="name" id="comment-name" placeholder="Enter your name">
</div>
<div class="single-input">
<input type="email" placeholder="Your email">
</div>
<div class="single-input">
<input type="text" name="phone" placeholder="Phone">
</div>
<div class="single-input">
<input type="text" name="subject" placeholder="Subject">
</div>
<div class="single-input textarea">
<textarea cols="3" name="message" rows="3" placeholder="Write your message here"></textarea>
</div>
<div class="single-input">
<button type="submit" class="cr-btn cr-btn--sm cr-btn--transparent cr-btn--icon"><span>send</span></button>
</div>
</form>
PHP Code:
<?php
// 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);
$subject = trim($_POST["subject"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($subject) 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 "Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "akcent.chester#gmail.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 .= "Subject: $subject\n\n";
$email_content .= "Phone: $phone\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.";
}
?>
js/ajax-mail.js file:
$(function() {
// Get the form.
var form = $('#contact-form');
// Get the messages div.
var formMessages = $('.form-message');
// 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.
$('#contact-form input,#contact-form textarea').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.');
}
});
});
});
<?php // 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"]);
$subject=trim($_POST["subject"]);
$message=trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($subject) 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 "Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient="example#gmail.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 .="Phone: $phone\n\n";
$email_content .="Subject: $subject\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.";
}
?>
<form id="#contact-form" action="mail.php" method="post">
<div class="single-input">
<input type="text" name="name" id="comment-name" placeholder="Enter your name">
</div>
<div class="single-input">
<input type="email" placeholder="Your email">
</div>
<div class="single-input">
<input type="text" name="phone" placeholder="Phone">
</div>
<div class="single-input">
<input type="text" name="subject" placeholder="Subject">
</div>
<div class="single-input textarea">
<textarea cols="3" name="message" rows="3" placeholder="Write your message here"></textarea>
</div>
<div class="single-input">
<button type="submit" class="cr-btn cr-btn--sm cr-btn--transparent cr-btn--icon"><span>send</span></button>
</div>
</form>
<div class="single-input">
<input type="email" placeholder="Your email">
</div>
This input element is missing a "name" attribute!

How to show success message below html form after form submit which is being handled by different php file

There is a form in my index.php file. This form is handling from a different php file named send-mail.php. I want to show a message inside alert div in index.php file. Can this be done by php or javascript will be needed too?
index.php:
<section id="contact">
<form action="send-mail.php" id="form" method="post" name="form">
<input id="name" name="name" placeholder="your name" type="text" required>
<input id="email" name="email" placeholder="your e-mail" type="email" required>
<textarea cols="50" id="message" name="message" placeholder="your enquiry" rows="4" required></textarea>
<input type="submit" name="submit" id="submit" value="Send Message">
</form>
<div class="alert alert-dismissible fade in hide" role=alert>
<button type=button class=close data-dismiss=alert aria-label=Close><span aria-hidden=true>×</span></button>
</div>
</section>
send-mail.php:
<?php
if(isset($_POST['submit'])){
// Get the submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Recipient email
$toEmail = 'user#example.com';
$emailSubject = 'Contact Request Submitted by '.$name;
$htmlContent = '<h2>Contact Request Submitted</h2>
<h4>Name</h4><p>'.$name.'</p>
<h4>Email</h4><p>'.$email.'</p>
<h4>Message</h4><p>'.$message.'</p>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";
// Send email
if(mail($toEmail,$emailSubject,$htmlContent,$headers)){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'alert-success';
header('location: index.php#contact');
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
$msgClass = 'alert-danger';
header('location: index.php#contact');
}
}
?>
Change your redirects to:
header('location: index.php?result='.$msgClass.'#contact');
Then adding the following to your index.php file:
if ($_GET['result']=="alert-success") {
// display success message here
} elseif ($_GET['result']=="alert-danger") {
// display error message here
}

"Undefined" response when submitting contact form without page refresh

I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.

Implementing $http.post in angular JS with PHP

I'm trying to send the message, name and email from a contact form on my index page to my own email but am having some troubles. I'm using AngularJS. Right now when I click submit on the form, it just comes up with a loading screen and nothing else ever happens. This is what I currently have:
HTML:
<form ng-submit="save()" class="contactForm" name="form" ng-hide="loaded" ng-controller="formCtrl">
<input class="input" required="required" type="text" name="name" placeholder="Your Name" ng-model="message.name" />
<input class="input email" required="required" type="email" name="email" value="" placeholder="Your Email" ng-model="message.email" /><br />
<textarea class="textarea" rows="5" required="required" placeholder="Your Message" ng-model="message.text" ></textarea>
<button class="btn green">Send Message</button>
</form>
JS:
$scope.save = function () {
$scope.loaded = true;
$scope.process = true;
$http.post('sendemail.php', $scope.message).success(function () {
$scope.success = true;
$scope.process = false;
});
};
PHP (sendemail.php):
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$email = $request->message.email;
$name = $request->message.name;
$message = $request->message.text;
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("myemail#gmail.com", $subject, $message, $from);
I've also tried the following php:
var_dump($_POST);die();
$_POST = json_decode($rest_json, true);
$email = $_POST["message.email"]; //$request->message.email;
$name = $_POST["message.name"]; //$request->message.name;
$message = $_POST["message.text"]; //$request->message.text;
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("myemail#gmail.com", $subject, $message, $from);
Should the php be in the same folder as the javascript? Any help would be much appreciated! Thanks very much.
You making POST ajax request, so in order to use data that you're trying to transfer to your PHP application, you need to find it in $_POST array. More about it here
More specifically you don't need this line $rest_json = file_get_contents("php://input");
You just need to get data from $_POST. Just make var_dump($_POST);die(); to debug what's in there and what you need to decode exactly.

HTML: Get value from text fields and email them

I am using bootstrap to create input fields. When someone clicks the "Submit" button I want the values (if they are valid) to be emailed to myself. I am having trouble even making sure they are valid. Below is my code
<form action="tryjs_submitpage.htm" onsubmit="return myFunction()">
<fieldset class="form-group">
<label for="name">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name">
</fieldset>
<fieldset class="form-group">
<label for="email">Email Address*:</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
</fieldset>
<fieldset class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" id="company" placeholder="Company Name">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function myFunction() {
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
submitOK = "true";
if (name.length == 0) {
alert("You must enter your name");
submitOK = "false";
}
if (email == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (message.length == 0) {
alert("You must enter a message");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
I modified the script from here, but when I click submit it says tryjs_submitpage.htm doesn't exist. Obviously this is an issue, but I can't seem to find tryjs_submitpage.htm anywhere to get it to work. Further I wanted to know if there was a way to trigger an email send with the appropriate information to my personal email. Thanks for the help!
You can't send an email directly with javascript for security reasons.
Suppose there is a feature in JavaScript to send email. Some malicious coder can write a script to send email to some address immediately when you visit their page. This will reveal your email address to some third party without your knowledge. They will start filling your mail box with lots of spam messages! However, there are alternatives as explained below. link
You can however open the user's mail client, to do so:
<form action="" onsubmit="sendMail(); return false">
...
...
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function sendMail() {
var link = "mailto:me#abc.com"
+ "?cc=myCCaddress#example.com"
+ "&subject=" + escape("This is my subject")
+ "&body=" + escape(document.getElementById('myText').value)
;
window.location.href = link;
}
</script>
You can't send a mail directly from the browser, however you can use third party technologies like http://www.emailjs.com/ or create a .php file using php native mail function to send mail.
Below is the HTML, JS(Jquery AJAX) and PHP file that handles mail sending.
In this case the PHP script handles email verification, but you can also use HTML require or JS regex to check at the client side before sending a POST request to the server
HTML
<form method="POST" action="" id="contactform">
<p>
<label for="name">Your Name</label>
<input type="text" name="name" class="input" >
</p>
<p>
<label for="email">Your Email</label>
<input type="text" name="email" class="input">
</p>
<p>
<label for="message">Your Message</label>
<textarea name="message" cols="88" rows="6" class="textarea" ></textarea>
</p>
<input type="submit" name="submit" value="Send your message" class="button transition">
</form>
JS (JQuery)
var $contactform = $('#contactform'),
$success = 'Your message has been sent. Thank you!',
$url = 'link to the hosted php script';
$contactform.submit(function(e) {
$.ajax({
type: 'POST',
url: $url,
data: $(this).serialize(),
dataType: "json",
xhrFields: {
withCredentials: true
}
})
.done(function(msg) {
console.log(msg)
if (msg.success == true) {
response = '<div class="success">' + $success + '</div>';
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Hide any previous response text.
$('.error, .success').remove();
// Show response message.
$contactform.prepend(response);
})
.fail(function(msg) {
console.log(msg)
});
e.preventDefault();
});
PHP
<?php
// Array to hold validation errors and response data.
$errors = array();
$data = array();
// Validate the variables
// if any of these variables don't exist, add an error to our $errors array
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: *');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'POST') {
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
}
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "admin#example.com";
$subject = "Website Contact Form: ".$name;
$headers = "From: noreply#example.com\n"; // email address the generated message will be from. Recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: ".$email;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
My advice is don't do the form validation yourself, just let the browser do it. You will need to change the input type on your email input to email, and you will need to add the required attribute to every one you want to be required.
This way instead of using JavaScript you can just use standards-compliant HTML.
Then, since you can't send email directly from the browser, you need a third-party service to send the email, like for example Formspree. Alternatively you could write a server-side script for sending email, but it's much easier to just use a service.
Here is the final code:
<form action="https://formspree.io/your.email.here#example.com">
<fieldset class="form-group">
<label for="usr">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name" name="message" required="required">
</fieldset>
<fieldset class="form-group">
<label for="exampleInputEmail1">Email Address*:</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email" required="required">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message" name="message" required="required"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
If you want to use Formspree and also have your visitors enter their company name, you can hack it by giving the company name field a name of "subject", which Formspree will forward to your email alongside the rest of the fields.
You have a little mistake in your code,
parameter document.getElementById is element id :
change code :
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
TO this :
var name = document.getElementById("usr").value;
var email = document.getElementById("exampleInputEmail1").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;

Categories