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

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!

Related

Why is form submit message displaying all characters from my index.html file?

When my message is submitted it goes to my email address and works fine, but the message success notification doesn't display 'Your message was sent successfully.', instead it displays all of the lines of code within my index file.
I think it has something to do with style="display: none".
Any idea how to show the 'Your message has been sent' message?
index.html
<div class="col-lg-5 mx-auto">
<div class="contact-form">
<div class="container">
<form class="contact-form" method="post" action="mail.php">
<!-- form message -->
<div class="row">
<div class="col-lg-12">
<div class="alert alert-success contact__msg" style="display: none" role="alert">
Your message was sent successfully.
</div>
</div>
</div>
<!-- end message -->
<!-- form element -->
<div class="form-group">
<label><strong>Name</strong></label>
<input name="name" type="text" class="form-control" placeholder="Enter Name" required>
</div>
<div class="form-group">
<label><strong>Email</strong></label>
<input name="email" type="email" class="form-control" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label><strong>Message</strong></label>
<textarea name="message" class="form-control" rows="3" placeholder="Enter Message" required></textarea>
</div>
<button name="submit" type="submit" class="btn btn-default"><span class="fa fa-paper-plane"></button></span>
<!-- end form element -->
</form>
</div>
</div>
mail.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
# FIX: Replace this email with recipient email
$mail_to = "*myemail*#gmail.com";
# Sender Data
$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($subject) OR empty($message)) {
# Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Please complete the form and try again.";
exit;
}
# Mail Content
$content = "Name: $name\n";
$content .= "Email: $email\n\n";
$content .= "Message:\n$message\n";
# email headers.
$headers = "From: $name <$email>";
# Send the email.
$success = mail($mail_to, $subject, $content, $headers);
if ($success) {
# 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, 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.";
}
?>
main.js
(function ($) {
'use strict';
var form = $('.contact-form'),
message = $('.contact__msg'),
form_data;
// Success function
function done_func(response) {
message.fadeIn().removeClass('alert-danger').addClass('alert-success');
message.text(response);
setTimeout(function () {
message.fadeOut();
}, 100000);
form.find('input:not([type="submit"]), textarea').val('');
}
// fail function
function fail_func(data) {
message.fadeIn().removeClass('alert-success').addClass('alert-success');
message.text(data.responseText);
setTimeout(function () {
message.fadeOut();
}, 100000);
}
form.submit(function (e) {
e.preventDefault();
form_data = $(this).serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form_data
})
.done(done_func)
.fail(fail_func);
});
})(jQuery);
Check the success function you specify the response but not the text to display.
e.g: message.text(response.??);
The field that contains the message from the back end script is not included so I’m guessing the issue is here. display:none is not the issue...

Bootstrap Alert Message not working

First - Im not an expert in PHP, but just know how to make some basic changes within contact form using PHP.
On this contact form when I filled in the required textfields and hit the submit button it redirects to the contact.php with a Contact form successfully submitted. Thank you, I will get back to you soon! message instead of displaying the message inside the <div class="messages"></div> on request-interpreter.html
HTML (form)
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div> <----- displays alert messages
<div class="controls">
<div class="row-form">
<div class="col-md-6">
<p class="text-req"><strong>*</strong> These fields are required. </p>
</div>
</div>
<div class="row-form">
<div class="col-md-6">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="First name *" required="required" data-error="First name is required." tabindex="1">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="Email *" required="required" data-error="Your email address is required." tabindex="3">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row-form">
<div class="col-md-6">
<div class="form-group">
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Last name *" required="required" data-error="Last name is required." tabindex="2">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Phone *" required="required" data-error="Your phone number is required." tabindex="4">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row-form">
<div class="col-md-12">
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Leave a message for us *" rows="4" required="required" data-error="Your important message is required." tabindex="5"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-success btn-send" value="Send Request" tabindex="6">
</div>
</div>
</div>
</form>
contact.php
<?php
// an email address that will be in the From field of the email.
$from = 'Contact form';
// an email address that will receive the email with the output of the form
$sendTo = $_POST['email'];
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// if you are not debugging and don't need error reporting, turn this off by
error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
Alert message AJAX
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (e.isDefaultPrevented()) {
var url = "contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox); <------ it should display the alert message, but its not working.
// empty the form
$('#contact-form')[0].reset();
}
}
});
}
})
});
You are echoing it (printing it) instead of returning the response, change it like this in your Contact.php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
return $encoded;
}
// else just display the message
else {
return $responseArray['message'];
}

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
}

send email from bootstrap framework My error in this is i got a message is Mail sent successfully but i didn't receive any mail

Form to send email from bootstrap frame work is that any thing i need to do extra work like adding phpmailer or need to change in php.ini file or need to setup any mail function
html code
<form name="sentMessage" id="contactForm" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name *" name="name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Your Email *" name= "email" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" class="form-control" placeholder="Your Phone *" name="phone" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Message *" name="message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<button type="submit" name="submit" class="btn btn-xl">Send Message</button>
</div>
</div>
</form>
js Codes
$(function () {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function ($form, event, errors) {
// additional error messages or events
},
submitSuccess: function ($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function () {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss = 'alert' aria - hidden = 'true' > & times; ").append("</button>");
$('#success > .alert-success').append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function () {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss = 'alert' aria - hidden = 'true' > & times; ").append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding.Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function () {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function (e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function () {
$('#success').html('');
});
This is my php file
<?php
// Check for empty fields
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'prasanna.venkatesan83#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to .
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n" . "Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: prasanna.venkatesan83#gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
$mail = #mail($to, $email_subject, $email_body, $headers);
if (!$mail->send()) {
echo "Cannot send e-mail";
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo "e-mail Has Been Sent To Your Email Address.";
return true;
?>
I believe the issue your facing is due to the built in php mail function not sending mail.
I recommend you use an external library such as swiftmail to send the mail for you.
Because we cannot see your smtp setting due to them been in your php.ini file which is not posted here we cannot evaluate them for you.
Your comments appear to point to the face the code is working fine but the mail is not sending as such the issue is with the php mail code.

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

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

Categories