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

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
}

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!

$error messate POST into div in index.php

This is my first question on this site however I have been here millions of times looking for answer and I hope you can help me out this time as I wasn't able to figure it out myself.
I am not very skilled when it comes to coding but was hoping to amend the php contact form I have found online (it's free), the form itself is worki9ng but what I am struggling with is to set the errors to be printed on the main page where the form is, at them moment the yare displayed on the contact.php form which is where the php code is and I would like it all displayed in a div for example on index.php just under the form.
my contact.php
<?php
if (isset($_POST['submit'])) {}
$sendTo = "email address";
$subject = "msg content";
$headers = 'From: email address' . "\r\n";
$name = #$_POST['name'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'thank you';
$errorMessage = 'Please fill all the fields';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "----------------------------------------";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
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 {
echo $responseArray;
}
?>
<form method="post" name="contactform" action="contact.php" >
<div class="field half first">
<label for="name">name</label>
<input type="text" name="name" id="name" placeholder="name" />
</div>
<div class="field half">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="email#email.com" />
</div>
<div class="field">
<label for="message">message</label>
<textarea name="message" id="msg" rows="4" placeholder="type your message here"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="----------------------------------"></div>
<ul class="actions">
<li><input type="submit" value="send" class="special" /></li>
<li><input type="reset" value="reset pola" /></li>
</ul>
I have tried to use $_POST and $_GET to echo responseArray but I can't figure it out...
Is anyone able to provide a code I would have to use to display $okMessage and $errorMessage on index.php please?
Many thanks for all help

Send contents of contact form direct to email via php [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have a contact form on my wordpress site but I cannot get information from the form to send to my email address when the submit button is clicked.
Once the submit button has been clicked and the email has been sent I would like a confirmation to appear underneath the submit button that the message has been sent/error if it hasn't. Note: I will update the css for the contact form to accommodate the extra text.
This is my form code:
<form action="secure_email.php" method="post" id="contact-form-content">
<h5>You have had a look, so let's get cracking. Email me at me#myemail.com or use this nifty thing.</h5><br></br>
<legend>Contact Form</legend>
<input type="text" placeholder="Full Name" name="full-name" id="full-name" required;><br></br>
<input type="text" placeholder="Email" name="email" id="email" required;><br></br>
<textarea placeholder="Message" name="message" id="message" rows="100" cols="100" wrap="hard" required;></textarea><br></br>
<button type="submit" name="submit" value="submit">Send</button>
</form>
And this is secure_email.php file:
<?php
if(isset($_POST['submit'])){
$to = "me#myemail.com"; // this is your Email address
$email = $_POST['email']; // this is the sender's Email address
$full-name = $_POST['full-name'];
$subject = "Form submission";
$message = $full-name . " " . $email . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
if (isset($_POST['submit']))
{
if (mail($to, $subject, $message, $headers))
echo "Thank you for contacting me!";
}
else
{
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
Just to update all this is the working code with contact form details being sent to my given email, the confirmation message appearing within the contact form and scroll back to contact form to see the confirmation message
<div id="contact-form">
<form action="#contact" method="post" id="contact-form-content">
<h5>You have had a look, so let's get cracking. Email me at me#myemail.com or use this nifty thing.</h5><br></br>
<legend>Contact Form</legend>
<input type="text" placeholder="Full Name" name="fullname" id="fullname" required;><br></br>
<input type="text" placeholder="Email" name="email" id="email" required;><br></br>
<textarea placeholder="Message" name="message" id="message" rows="100" cols="100" wrap="hard" required;></textarea><br></br>
<button type="submit" name="submit" value="submit">Send</button>
<?php
if(isset($_POST['submit'])){
$to = "me#myemail.com"; // this is your Email address
$email = $_POST['email']; // this is the sender's Email address
$fullname = $_POST['fullname'];
$subject = "Form submission";
$message = $fullname . " " . $email . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if (mail($to, $subject, $message, $headers)){
echo "Thank you for contacting me!";
}
else
{
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
</form>
</div>
</div>
Please use mail functions.
PHP Mail Function
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
WordPress Mail Function
wp_mail($to, $subject, $message, $headers);
You eitherneed to
use Ajax to post your form data to secure-email.php then add the success message on succes in JavaScript.
Or
Post to the same page as the form, detect if the form has been submitted and send your email, then echo your success message if the mail sends successfully. The page will refresh when they hit submit and the message will be displayed.

php mail with .js validation -> can't see any mistakes

I got this piece of code from a free template and I followed all the instructions that came with it, everything seems fine but mail doesn't go trough.
HTML:
<!--Start Contact form -->
<form name="enq" method="post" action="email/" onsubmit="return validation();">
<fieldset>
<input type="text" name="name" id="name" value="" class="input-block-level" placeholder="Name.." />
<input type="text" name="email" id="email" value="" class="input-block-level" placeholder="Email.." />
<textarea rows="11" name="message" id="message" class="input-block-level" placeholder="Message.."></textarea>
<div class="actions">
<input type="submit" value="Send!" name="submit" id="submitButton" class="btn btn-info pull-right" title="Send!" />
</div>
</fieldset>
</form>
<!--End Contact form -->
PHP
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="email#sample.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
else
header("Location:../contact.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
?>
JavaScript
function validation()
{
var contactname=document.enq.name.value;
var name_exp=/^[A-Za-z\s]+$/;
if(contactname=='')
{
alert("Name Field Should Not Be Empty!");
document.enq.name.focus();
return false;
}
else if(!contactname.match(name_exp))
{
alert("Invalid Name field!");
document.enq.name.focus();
return false;
}
var email=document.enq.email.value;
//var email_exp=/^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp=/^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if(email=='')
{
alert("Please Enter Email-Id!");
document.enq.email.focus();
return false;
}
else if(!email.match(email_exp))
{
alert("Invalid Email ID !");
document.enq.email.focus();
return false;
}
var message=document.enq.message.value;
if(message=='')
{
alert("Query Field Should Not Be Empty!");
document.enq.message.focus();
return false;
}
return true;
}
I don't get any errors but mail doesn't simply go trough, checked spam etc.
I hope you changed
$to="email#sample.com";
to your actual e-mail.. I can't see anything else.
Seems it was due to webhost(mailserver). Works like a charm on another webhost.

add email validation prior to submitting on php form

I have the following simple form that I am trying to get the email validation error to
show up within the form to show the error prior to submitting.
Is there a way to do this with PHP or do I have to use JSON?
If I have to use JSON, can anyone show me how to do this?
Thanks in advance.
form.html:
<form method="post" name="form" action="form.php">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<div id="error"></div>
form.php
<?php
// send to and from
$to = "email#example.com";
$headers = "From: email#example.com \r\n";
$headers .= "Reply-To: email#example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body =
"A message from your website contact form \n\n".
"Email: $email \n\n".
"Phone: $phone \n\n".
"From: $name \n\n".
"Message: \n".
"$message \n";
// honeypot
if($robot)
header( "Location: http://www.example.com/nothankyou.html" );
else{
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '<div id="error">Please Enter a Valid Email</div>';
}
else
{
// send it
mail($to,$email_subject,$email_body,$headers);
header( "Location: http://www.example.com/thankyou.html" );
}
}
?>
You could try using a javascript/jquery plugin to do your front end validation (ex. http://jqueryvalidation.org/, http://bootstrapvalidator.com/). If you still wanted to keep your existing code I'd suggest something like:
First, merge your form.html to form.php
Make sure your php mailing code stays at the top of the file because php headers cannot have any output done before calling them.
<?php
if (count($_POST)) {
// send to and from
$to = "email#example.com";
$headers = "From: email#example.com \r\n";
$headers .= "Reply-To: email#example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body = "A message from your website contact form \n\n" .
"Email: $email \n\n" .
"Phone: $phone \n\n" .
"From: $name \n\n" .
"Message: \n" .
"$message \n";
// honeypot
if ($robot)
header("Location: http://www.example.com/nothankyou.html");
else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: form.php?error=email_error");
} else {
// send it
mail($to, $email_subject, $email_body, $headers);
header("Location: http://www.example.com/thankyou.html");
}
}
}
?>
<form method="post" name="form" action="">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<?php
if (isset($_GET["error"]) && $_GET["error"] == "email_error") {
?>
<div id="error">Please Enter a Valid Email</div>
<?php
}

Categories