This question already has answers here:
(PHP) Stuck making submission form anti spam
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
When I open the email the message is always empty, I get the name and email but message is empty,
I recently added google recaptcha v3 which was giant pain , but It is now working.
anyway I tried to debug this, and It show no errors, the message textarea send to email but I receive it empty...
this is the form
<?php
if(isset($_POST['submit'])){
$captcha=$_POST['token'];
$secret = 'censord';
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
);
// use json_decode to extract json response
$response = json_decode($response);
if($response->success == true) {
//save data to database
echo '<div class="alert alert-success">
<strong>Success!</strong> Data is saved.
</div>';
} else {
echo '<div class="alert alert-warning">
<strong>warning!</strong> Failed to save data.
</div>';
}
}
?>
<style>
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$name = htmlspecialchars(stripslashes(trim($_POST['username'])));
$email = htmlspecialchars(stripslashes(trim($_POST['email'])));
$text = htmlspecialchars(stripslashes(trim($_POST['textt'])));
if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
$name_error = 'Invalid name';
}
if(!preg_match("/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
$email_error = 'Invalid email';
}
if(strlen($text) === 0){
$message_error = 'Your message should not be empty';
}
if(preg_match('/http|www/i',$comments)) {
$error_message .= "We do not allow a url in the comment.<br />";
}
}
?>
<div id="container">
<div class="form-wrap">
<h1>Report bug</h1>
<p>Report us if you find any bug or broken link in our free online programming classes.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<div class="form-group">
<label for="username">Name:</label>
<input type="text" name="username">
<p><?php if(isset($name_error)) echo $name_error; ?></p>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email">
<p><?php if(isset($email_error)) echo $email_error; ?></p>
</div>
<div class="form-group">
<label for="textt">Message:</label>
<textarea type="text" name="textt" rows="22" cols="42"></textarea>
<p><?php if(isset($message_error)) echo $message_error; ?></p>
</div>
<button type="submit" name="submit" value="Submit" class="btn">Report us</button>
<input type="hidden" name="action" value="validate_captcha">
<?php
if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
$to = 'censord'; // edit here
$body = " Name: $name\n E-mail: $email\n Message:\n $message";
if(mail($to, $subject, $body)){
echo '<p style="color: green">Message sent</p>';
}else{
echo '<p>Error occurred, please try again later</p>';
}
}
?>
</form>
</div>
</div>
</body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('censord', {action: 'validate_captcha'}).then(function(token) {
console.log(token);
document.getElementById("token").value = token;
});
});
</script>
</html>
Related
I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>
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
I am following a guide to build a bootstrap contact form and submit it through mail.php without having to reload the page using ajax. I am able to get the form to work up until I try implementing ajax. I get stuck because the instructions arent clear as to which code exactly needs to be replaced and where the new code is supposed to go. Here is a link to the guide I am following and the section I am stuck at:
Sending email without reloading page using AJAX
This is the site I am trying to get it to work on: CRANE TECH. NET
I am not so familiar with php so I'm thinking that is where I am messing it up at.
Here is the exact code I am using:
HTML
<section class="section">
<h2 class="section-heading text-muted h4 pt-4">Free Consultation</h2>
<!--CONTACT DESCRIPTION-->
<p class="section-description">Are you ready to turn your vision into a reality? Fill out the contact form below and a member of our team will get back to you as soon as possible. Let's bring your idea to life!</p>
<div class="row">
<div class="col-12">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row">
<!--NAME INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="* NAME" required>
<label for="name" class=""></label>
</div>
</div>
<!--EMAIL INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="email" name="email" class="form-control" placeholder="* EMAIL" required>
<label for="email" class=""></label>
</div>
</div>
</div>
<div class="row">
<!-- PHONE NUMBER INPUT -->
<div class="col-12">
<div class="md-form">
<input type="text" id="clientPhone" name="clientPhone" class="form-control" placeholder="PHONE" required>
<label for="phone number" class=""></label>
</div>
</div>
<!--SUBJECT INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="subject" name="subject" class="form-control" placeholder="* SUBJECT" required>
<label for="subject" class=""></label>
</div>
</div>
</div>
<div class="row">
<!--MESSAGE INPUT-->
<div class="col-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="3" class="form-control md-textarea" placeholder="* MESSAGE" required></textarea>
<label for="message"></label>
</div>
</div>
</div>
</form>
<!-- SUBMIT BUTTON -->
<div class=" col-3 offset-3 offset-md-4 mb-4">
<button class="btn btn-warning" onclick="validateForm()">Send <i class="fa fa-paper-plane ml-1"></i></button>
</div>
<div id="status" class="text-muted col-12 col-md-8 offset-md-2 my-1"></div>
</div>
JS
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
return false;
} else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(email)) {
document.getElementById('status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
return false;
}
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'clientPhone': $('input[name=clientPhone]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
document.getElementById('contact-form').submit();
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
}
MAIL.PHP
<?php
if(isset( $_POST['name']))
$name = $_POST['name'];
if(isset( $_POST['email']))
$email = $_POST['email'];
if(isset( $_POST['clientPhone']))
$clientPhone = $_POST['clientPhone'];
if(isset( $_POST['subject']))
$subject = $_POST['subject'];
if(isset( $_POST['message']))
$message = $_POST['message'];
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
// if ($name === ''){
// echo "Name cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($email === ''){
// echo "Email cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// } else {
// if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
// echo "Email format invalid.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// }
// if ($subject === ''){
// echo "Subject cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($message === ''){
// echo "Message cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
$content="From: $name \n Email: $email \n Phone #: $clientPhone \n Subject: $subject \n Message: $message";
$recipient = "support#crane-tech.net";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!', 'code' => 1));
exit();
?>
Main Issue
You main issue is that there is a missing semcolon (;) and the end of line 15 in the php code.
Other Issues
Your website is using JQuery Slim, $.ajax is not included in the slim version so you are getting an error due to that. To fix this just include the full JQuery or do the ajax without JQuery.
You may also want to get rid of this line:
document.getElementById('contact-form').submit();
because it is causing a redirect when you are already manually submitting your data.
You should remove these lines because you have already set them:
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
Unrelated note:
If you are already using JQuery, you should be using it - instead of doing this:
document.getElementById('status')
You should be using:
$('#status')
I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php
Hi having a problem with my contact form submission ,Its a Bootstrap template, its got JQuery validation, but there wasn't any PHP file for contact, i tried many different code for contact.php but it doesn't work,
some of them showing "message sent successfully" but i didn't receive any email. i am using "Google Apps For Work" as my email client only. please help, really appreciate.
(Sorry about my poor English.)
Here the code for index.php`
<form action="Contact.php" method="post" id="sky-form3" class="sky-form contact-style">
<fieldset>
<label>Name</label>
<div class="row">
<div class="col-md-7 margin-bottom-20 col-md-offset-0">
<div>
<input type="text" name="name" id="name" class="form-control">
</div>
</div>
</div>
<label>Email <span class="color-red">*</span></label>
<div class="row">
<div class="col-md-7 margin-bottom-20 col-md-offset-0">
<div>
<input type="text" name="email" id="email" class="form-control">
</div>
</div>
</div>
<label>Message</label>
<div class="row">
<div class="col-md-11 margin-bottom-20 col-md-offset-0">
<div>
<textarea rows="8" name="message" id="message" class="form-control"></textarea>
</div>
</div>
</div>
<p><button type="submit" class="btn-u btn-brd btn-brd-hover btn-u-dark">Send Message</button>
<button type="reset" class="btn-u btn-brd btn-brd-hover btn-u-dark">Reset Messages</button></p>
</fieldset>
<div class="message">
<i class="rounded-x fa fa-check"></i>
<p>Your message was successfully sent!</p>
</div>
</form>
Here the code for my contact.php file
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
<?php
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'contact#vertigosourcing.com';
$name = addslashes(trim($_POST['name']));
$Email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
$array = array('nameMessage' => '', 'emailMessage' => '', 'messageMessage' => '');
if(!isEmail($Email)) {
$array['emailMessage'] = 'Invalid email!';
}
if($subject == '') {
$array['nameMessage'] = 'Empty name!';
}
if($message == '') {
$array['messageMessage'] = 'Empty message!';
}
if(isEmail($Email) && $name != '' && $message != '') {
// Send email
$headers = "From: " . $Email . " <" . $Email . ">" . "\r\n" . "Reply-To: " . $Email;
mail($emailTo, $subject . " (contact request from)", $message, $headers);
}
}
?>
If you are using xampp/lamp/wamp, it won't work that easy, you have to activate some functions to send an email from a localhost, I think that's the problem because you have no mistakes in your code.
You can also try using #mail() instead of mail().