I have a contact form on my website that with the current code sends an email to the sender and the receiver, and all works fine. However, once completing the form, the page opens email.php instead of showing a popup that I hoped it would. I have no idea how to fix as I'm not used to writing for php and JS. Below is my code.
<form method="post" action="email.php" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_self" novalidate>
<input type="text" value="" name="full_name" class="fullname" id="mce-name" placeholder="full name" required>
<input type="text" value="" name="phone_num" class="phonenum" id="mce-phone" placeholder="phone number" required>
<br>
<input type="email" value="" name="email" class="email" id="mce-EMAIL" placeholder="email address" required>
<div style="position: absolute; left: -5000px;"><input type="text" name="b_cdb7b577e41181934ed6a6a44_e65110b38d" value=""></div>
<div class="clear"><input type="submit" value="Submit" name="submit" id="mc-embedded-subscribe" class="button"></div>
</form>
<?php
if(isset($_POST['submit'])){
$to = "email#help.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$full_name = $_POST['full_name'];
$phone_num = $_POST['phone_num'];
$subject = "Title";
$subject2 = "Copy of your form submission";
$message = "Message";
$message2 = "Message2";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
if ($_POST['submit']) {
if ($name != '' && $email != '' && $subject != '' && $message != '') {
}
} else {
echo '<script>function displayPopup()
{
alert("Form submitted!");
}<script>';
}
}
?>
because you only declare the popup function, you did not run displayPopup()
try to change to
if ($_POST['submit']) {
if ($name != '' && $email != '' && $subject != '' && $message != '') {
} else {
echo '<script>function displayPopup(){alert("Form submitted!");}';
echo 'displayPopup();</script>
';
}
}
Related
I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax
From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH
I have the following code for my HTML Form with PHP on the same page. Actually, the problem is that when anybody opens the website it automatically runs the PHP Mail() script and send me an empty mail.
I want it to work only when somebody successfully submits the form. Please help.
<!--HTML FORM--><form method="post" name="contactform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateform()">
<input type="text" name="fullname" class="fullname" placeholder="Full Name*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Full Name*';}">
<input type="text" name="email" class="email" placeholder="Email Address*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Email Address*';}">
<textarea placeholder="Your Message*:" name="message" class="message"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Your Message*';}"></textarea>
<input type="submit" name="submit" value="Submit" />
</form><!--/HTML FORM> <!--Contact Form PHP-->
<?php
// define variables and set to empty values
$fullname = $email = $message = "";
$subject="Message from Website Visitor:".test_input($_POST["fullname"]);
$to="camadhusudanmishra#gmail.com";
$headers = "From:".test_input($_POST["email"]);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$email = test_input($_POST["email"]);
$message = test_input($_POST["message"]);}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
$message = str_replace("\n.", "\n..", $message);
mail($to,$subject,$message,$headers);
?>
<!--/Contact Form PHP-->
JS Code for Validation:
function formValidation() {
var fullname = document.contactform.fullname;
var email = document.contactform.email;
var message = document.contactform.message;
if(validateName(fullname))
{
if(validateEmail(email))
{
if(validateMessage(message))
{
}
}
}
return false;
}
function validateName(fullname)
{
var letters = /^[A-Za-z]+$/;
if(fullname.value.match(letters) && fullname.value.length >= 3 && fullname.value.length <= 30)
{
return true;
}
else {
alert('Please enter a valid name');
return false;
}
}
function validateEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
return false;
}
}
function validateMessage(message)
{
if(message.value.length >=5 && message.value.length <=300)
{
alert('Form Succesfully Submitted');
window.location.reload();
return true;
}
else
{
alert("Please type a valid message.");
return false;
}
}
You can use following code.
<?php
if(isset($_POST['submit']))
{
// Add here function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
// define variables and set to empty values
$fullname = $email = $message = "";
$subject="Message from Website Visitor:".test_input($_POST["fullname"]);
$to="camadhusudanmishra#gmail.com";
$headers = "From:".test_input($_POST["email"]);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fullname = test_input($_POST["fullname"]);
$email = test_input($_POST["email"]);
$message = test_input($_POST["message"]);}
$message = str_replace("\n.", "\n..", $message);
mail($to,$subject,$message,$headers);
}
?>
<!--/Contact Form PHP-->
<!--HTML FORM-->
<form method="post" name="contactform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateform()">
<input type="text" name="fullname" class="fullname" placeholder="Full Name*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Full Name*';}">
<input type="text" name="email" class="email" placeholder="Email Address*"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Email Address*';}">
<textarea placeholder="Your Message*:" name="message" class="message"
onfocus="this.placeholder = '';" onblur="if (this.placeholder == '') {this.placeholder = 'Your Message*';}"></textarea>
<input type="submit" name="submit" value="Submit" />
</form><!--/HTML FORM> <!--Contact Form PHP-->
I purchased a theme, and I need to make a processing.php for my contact form. The form that sends the data to the server for processing.
This is the form code:
<div class="form_error text-center">
<div class="name_error hide error">Please Enter your name</div>
<div class="email_error hide error">Please Enter your Email</div>
<div class="email_val_error hide error">Please Enter a Valid Email Address</div>
<div class="message_error hide error">Please Enter Your Message</div>
</div>
<div class="Sucess"></div>
<form role="form">
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" id="name" placeholder="Name">
<input type="email" class="form-control" id="email" placeholder="Email">
<input type="text" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="col-md-8">
<textarea class="form-control" id="message" rows="25" cols="10" placeholder=" Message Texts..."></textarea>
<button type="button" class="btn btn-default submit-btn form_submit">SEND MESSAGE</button>
</div>
</div>
</form>
Both shubham and adi's answers are vulnerable to SMTP header injections, allowing your contact form to be used to send spam. It will happen.
Any POST or GET data passed to the additional_headers parameter needs to be sanitised to prevent abuse.
See the following:
http://php.net/manual/en/function.mail.php
https://www.phpsecure.info/v2/article/MailHeadersInject.en.php
see this example
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['contact_name'])&&isset($_POST['contact_mail'])&&isset($_POST['message'])) {
$contact_name = $_POST['contact_name'];
$contact_mail = $_POST['contact_mail'];
$message = $_POST['message'];
if (!empty($contact_name) && !empty($contact_mail) && !empty($message)) {
$to = 'your email#gmail.com'; // this is where you want to send the email
$subject = 'Contact form Submitted';
$body = $contact_name."\n".$message;
$headers = 'From:'.$contact_mail; // email of the sender
if (#mail($to, $subject, $body, $headers)) {
echo 'Thanks for contacting us';
}
else {
echo 'Sorry, an error has been occurred';
}
}
else {
echo 'All fields are required';
}
}
?>
<form action="index.php" method="POST">
Name:<br>
<input type="text" name="contact_name"></input><br><br>
Email Address:<br>
<input type="text" name="contact_mail"></input><br><br>
Message:<br>
<textarea name="message" cols="30" rows="6"></textarea><br><br>
<input type="submit" value="Send"></input>
</form>
maybe this codes can help you
I've a website since 2013. I've signed up quite 12k users. From 5 months I have noticed some blank users. They receive a user-code but "name" "surname" and "email" fields are blanks.
This event happen every 50/100 users registrations. Why? I have tried everything, but in all test I can't sign up without data. Also other people that have made tests can't sign up without insert data.
This is the form:
<form action="script/****.php" method="post" onsubmit="return validate()">
<label for="name">Name</label>
<input type="text" id="name" name="name" <?php if($_REQUEST['name'] != "") echo "value='".$_REQUEST['name']."'"; ?> />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" <?php if($_REQUEST['surname'] != "") echo "value='".$_REQUEST['surname']."'"; ?> />
<label for="email">Email</label>
<input type="email" id="email" name="email" <?php if($_REQUEST['email'] != "") echo "value='".$_REQUEST['email']."'"; ?> />
<label for="c_email">Retype Email</label>
<input type="email" id="c_email" name="c_email" />
<label for="password">Password</label>
<input type="password" id="password" name="password" />
<label for="c_password">Retype Password</label>
<input type="password" id="c_password" name="c_password" />
<input type="submit" value="registrati" />
</form>
This is the code that stores data on db:
<?php
function mt_rand_str ($length, $available = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789') {
for ($string = '', $i = 0; $i < $length; ++$i) {
$string .= $available[mt_rand(0, strlen($available)-1)];
}
return $string;
}
include('connection.php');
$con = connection();
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$bonus = 10;
$today = new DateTime();
$signUpDate = $today->format('Y-m-d');
if(strpos($name,' ') !== false) {
echo "
<script>
alert('Nome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($surname,' ') !== false) {
echo "
<script>
alert('Cognome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($email,' ') !== false) {
echo "
<script>
alert('Email non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($password,' ') !== false) {
echo "
<script>
alert('Password non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
connectionCheck($con);
userDbCheck($con);
$checkEmail = mysqli_query($con,"Select * from Users_DB where email = '$email'");
if(!mysqli_fetch_assoc($checkEmail)) {
do {
$userCode = mt_rand_str(8);
}
while(mysqli_fetch_assoc(mysqli_query($con,"select * from Users_DB where binary UserCode = '$userCode'")));
$value = 20;
mysqli_query($con,"Insert into User_DB (UserCode,Name,Surname,Phone,Email,Password,SignUpDate,bonus)
values ('$userCode','$name','$surname','','$email','$password','$signUpDate','$bonus')");
}
else {
echo "
<script>
alert('Email exists already!');
window.location.href = '../signup.php';
</script>";
}
?>
I hope you can find what I have not. As you can see, I've put in php code some data check too.
So I have
1) HTML5 check: type="email". I'm thinking to put also "pattern match" in all fields
2) JavaScript check
3) PHP check
I'm so desperate...
Thank you before.
html code:
Contact Me
<label for="Name">Name:</label>
<input type="text" name="name" id="Name" accesskey="N" tabindex="1">
<label for="Email">E-mail:</label>
<input type="text" name="email" id="Email" accesskey="E" tabindex="1">
<label for="Phone">Phone Number:</label>
<input type="text" name="number" id="Number" tabindex="1">
<label for="Comment">Comments</label>
<textarea type="text" name="comment" id="Comment" rows="27" cols="70" tabindex="1"></textarea>
<input id="mySubmit" type="submit" value="Submit">
</form>
</fieldset>
</div>
email.php
<?php
if (isset($_POST['submit'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email)
echo "<script type='text/javascript'>alert('Please enter a valid email address...');history.back();</script>";
else {
$to = "randomemail#gmail.com"; //change this to YOUR email address
$name = (isset($_POST['name'])) ? $_POST['name'] : "anonymous";
$number = (isset($_POST['number'])) ? $_POST['number'] : "none";
$comment = (isset($_POST['comment'])) ? $_POST['comment'] : "none";
$subject = "Message from $name via contact form";
$message = "Name: $name\nNumber: $number\nEmail: $email\nMessage: $comment";
$from = "From: " . $name . "<" . $email .">\r\n" .
"Reply-To: " . $email ."\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $from))
header("Location: thanks.html");
else
echo "<script type='text/javascript'>alert('An unknown system error has occurred!');history.back();</script>";
}
}
?>
when you submit, it loads email.php, but only a white page, not the thanks.html that it should.
You forgot to name your submit field:
<input id="mySubmit" type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Don't use form fields to detect a post. Use the 100% reliable:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
instead. This will ALWAYS be true if a POST was performed. As you can see with your version, a simple typo or oversight will completely kill your logic.
First Empty your file and just put header("Location: thanks.html"); in your php tags. If it works then add the other lines progressively. you'll see the annoying line. Read about header on PHP reference website. It should be used carefully