How do I force form submit with Jquery - javascript

Wish you all a happy 2015!
I have a simple contact us php form. I am validating it with parsley.js. The validation works fine but I am receiving a lot of spam mails.
I believe if I can force the form to be submitted only if Jquery is enabled, then it should solve my problem (right?).
I'm not an expert with PhP/ Jquery and any help will be appreciated.
Here is my PHP code
<?php
// Define Variables i.e. name tag, as per form and set to empty
$contact_name = $contact_email = $contact_phone = $contact_message = "";
// Sanitize data and use friendly names
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["contact_name"]);
$email = test_input($_POST["contact_email"]);
$phone = test_input($_POST["contact_phone"]);
$message = test_input($_POST["contact_message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Set values
$to = 'info#foryourservice.in';
$subject = 'New Message from Website';
$headers = 'From: info#domainname.com' . "\r\n" .
'Reply-To: info#domainname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Set Email content
$emailcontent = "A new message has been submitted from the website.
\n
Name : $name
Email : $email
Phone : $phone
Message : $message";
// Mail function
$send_contact=mail($to,$subject,$emailcontent,$headers);
if($send_contact){
header('Location: index.php#contactusform');
}
else {
echo "<script type='text/javascript'>alert('We encountered an ERROR! Please go back and try again.');</script>";
}
?>
Here is my HTML ( Im using Twitter Bootstrap)
<form role="form" method="POST" action="contactusform.php" id="contactusform" data-parsley-validate>
<div class="col-xs-6">
<div class="form-group" style="margin-bottom: -5px">
<label for="input1"></label>
<input type="text" name="contact_name" class="form-control" id="input1" placeholder="Name*" required data-parsley-required-message="Please enter your name">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input2"></label>
<input type="email" name="contact_email" class="form-control" id="input2" placeholder="Email Address*" data-parsley-trigger="change" required data-parsley-required-message="Please enter a valid Email address">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input3"></label>
<input type="tel" name="contact_phone" class="form-control" id="input3" placeholder="Phone Number*" required data-parsley-type="digits" data-parsley-minlength="10" data-parsley-maxlength="10" data-parsley-required-message="Please enter a 10 digit number">
</div>
<br>
<div class="form-group">
<button type="submit" id="contactbutton" class="btn btn-primary" style="background-color: #A8B645; border-color: transparent">Submit</button>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="input4"></label>
<textarea name="contact_message" class="form-control" rows="7" id="input4" placeholder="Message*" required required data-parsley-required-message="Say something!"></textarea>
</div>
</div>
</form>
This is what the Spam Email looks like :
A new message has been submitted from the website.
Name : お買い得アナスイ ミロード大壳り出しランキング
Email : rsilau#gmail.com
Phone : お買い得アナスイ ミロード大壳り出しランキング
Message : Shoppers takes the boast on bag
お買い得アナスイ ミロード大壳り出しランキング http://www.frkapaun.org/dyqfmnwg/ysl-annasuixmraAekm.asp

Add a hidden field to your form:
<input type="hidden" value="0" id="botcheck" name="botcheck" />
Then with jQuery set the value to 1:
$("#botcheck").val("1");
Then server-side check the value of $_POST["botcheck"].

You might want to check if your form is submitted using ajax:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Process form here
}
For further explanation

Related

Wordpress PHP Contact form - problem with displaying message about sent mail

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>

theme php contact form

I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});

Display message after php form submit INSIDE same page

on my INDEX.HTML page I have a subscription form that writes data to a DB with php. Everything works honky-dori.
When I submit the form the site goes to the PHP file I use to submit the emails to me and the visitor. I then can echo a thank you message. However...I dont want the message to appear inside this php page....I want the form to disappear and the message appear on my index page inside a a tag...e.g a DIV.
How do I do this? If I need to use AJAX or JQUERY...could you please point me to the right place?
Here are some of the code:
<div class="container-fluid">
<form action="thankyou.php" method="post">
<div class="form-group">
<label for="firstname">First Name:</label>
<input type="input" class="form-control" id="firstname" name="firstname">
<label for="lastname">Last Name:</label>
<input type="input" class="form-control" id="lastname" placeholder="" name="lastname">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="" name="email">
</div>
<button type="submit" class="btn btn-warning">Submit</button>
</form>
</div>
thankyou.php
<?php
require 'connection.php';
$conn = Connect();
$firstname = $conn->real_escape_string($_POST['firstname']);
$lastname = $conn->real_escape_string($_POST['lastname']);
$email = $conn->real_escape_string($_POST['email']);
$myemail = "myemailaddress";
$query = "INSERT into subscription (firstname,lastname,email) VALUES('" . $firstname . "','" . $lastname . "','" . $email . "')";
$success = $conn->query($query);
$subject1 = "New eBook Subscriber";
if (!$success) {
die("Couldn't enter data: ".$conn->error);
} else {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: ' .$myemail. "\r\n";
$message = "some message";
$messageb = "some message";
mail($email, $subject, $messageb, $headers);
mail($myemail, $subject1, $message, $headers);
?><META HTTP-EQUIV="Refresh" CONTENT="1;URL=index.html">
<?php
$conn->close();
}
?>
Try this solution
<div class="container-fluid">
<form action="thankyou.php" method="post" id="form">
<div class="form-group">
<label for="firstname">First Name:</label>
<input type="input" class="form-control" id="firstname" name="firstname">
<label for="lastname">Last Name:</label>
<input type="input" class="form-control" id="lastname" placeholder="" name="lastname">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="" name="email">
</div>
<button type="submit" class="btn btn-warning">Submit</button>
</form>
</div>
<script>
$('#form').on('submit', function(event) {
event.preventDefault(); //stops form on submit
var formData = {};
$.each($("#form").serializeArray(), function (i, field) {
formData[field.name] = field.value;
});
$.ajax({
url: 'thankyou.php',
data: formData,
method:'POST',
success: function(response) {
$(this).hide(); //sets css display:none to form
var message = "Thank you!";
$('.container-fluid').html(message);
}
});
});
</script>
Set the redirect after the successfully email the data and set a session variable and print this session variable in the html page. this may solve your problem however you can also use ajax to send the data and solve this problem.

Form submission success message not displaying

I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \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;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}

php script sending blank emails not able to fetch post data

PHP code at the top of index.php. Whenever I click on submit it displays message sent but it generates a blank email to my email address its not catching data from post.
<?php
$emailSubject = 'Customer Has a Question!';
$webMaster = 'admin#princosoft.com';
$name = $_POST['iname'];
$email = $_POST['iemail'];
$phone=$_POST['iphone'];
$question = $_POST['imessage'];
echo $name;
$body = <<<EOD
<br><hr><br>
Name: $name <br>
Email: $email <br>
Questions: $question <br>
EOD;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);
$theResults = <<<EOD
EOD;
echo "$theResults";
?>
<div class="col-lg-12">
<form name="sentMessage" action="/index.php" method="post" id="contactForm" novalidate >
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="iname" class="form-control"
placeholder="Your Name *"
id="name"
required data-validation-required-message="Please enter your name.">
<?php $name = $_POST['iname']; ?>
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" name="iemail" class="form-control"
placeholder="Your Email *" id="email"
required data-validation-required-message="Please enter your email address.">
<?php $name = $_POST['iemail']; ?>
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" name="iphone"
class="form-control"
placeholder="Your Phone *" id="phone"
required data-validation-required-message="Please enter your phone number.">
<?php $name = $_POST['iphone']; ?>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control"name="imessage" placeholder="Your Message *"
id="message"
required data-validation-required-message="Please enter a
message.">/textarea>
<?php $name = $_POST['imessage']; ?>
<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="isubmit" class="btn btn-xl">Send Message</button>
</div>
</div>
</form>
This is all the code of html + php
Okay just looking at it, there is a lot wrong here.
First of all, I am not a big fan on EOD. so, I change that to just to quotations.
Your text needs indenting, seriously, else you cant read it.
Let me first give you the php, then the html.
<?php
print_r($_POST);
if (isset($_POST['isubmit'])){ // checking if the submit button variable is there from clicking on the button
// mail variables
$emailSubject = 'Customer Has a Question!';
$webMaster = 'admin#princosoft.com';
$name = $_POST['iname'];
$email = $_POST['iemail'];
$phone=$_POST['iphone']; // please note this variable is not used anymore in the code. You either forgot it in your email, or you dont want anything with this
$question = $_POST['imessage'];
echo $name;
//set up mail body
$body = "<br><hr><br>";
$body .= "Name:". $name . "<br>";
$body .= "Email:". $email ."<br>";
$body .= "Questions:". $question ."<br>";
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
if (mail($webMaster, $emailSubject, $body, $headers)){
echo "your mail has been send succesfully";
}
} else {
// this is a test message. Just erase the whole else statement when this all works (for test purposes if the code is read)
echo "variables aren't set yet"
}
?>
As you see, i did some alterations to your code. I make sure it checks to see if the variables are set up. This way, you can trigger the mail with all variables in it. Now it runs everytime you refresh the page the mail function. You wouldn't wanna do that. I did a check as well on the mailfunction if it has send the messages, and I added an extra header to it.
What you should try to do is sanatize your input. Now it doesn't end up in a database so its not much of a big issue, however, what if you do wanna send it to your own database for reference? Its a simple matter of adding a function called mysqli_real_escape_string() (asuming you work with mysqli if you have database functions on your site running. Check that out if you will.
<form name="sentMessage" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="contactForm" novalidate >
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="iname" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
<?php $name = $_POST['iname']; // i leave this here, but i would remove this. It has no purpose, if you want to replace the name in your field, check if variable is set, and put it in the name field of your item ?>
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" name="iemail" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
<?php $name = $_POST['iemail']; // i leave this here, but i would remove this. It has no purpose, if you want to replace the name in your field, check if variable is set, and put it in the name field of your item ?>
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" name="iphone" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
<?php $name = $_POST['iphone'];// i leave this here, but i would remove this. It has no purpose, if you want to replace the name in your field, check if variable is set, and put it in the name field of your item ?>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control"name="imessage" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea> <!-- issue here with wrong closing of text area in html -->
<?php $name = $_POST['imessage']; // i leave this here, but i would remove this. It has no purpose, if you want to replace the name in your field, check if variable is set, and put it in the name field of your item ?>
<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="isubmit" class="btn btn-xl">Send Message</button>
</div>
</div>
</form>
Also I looked at your html. The key here is called indenting. There is some questionable placement of php, which I didnt get. The echo's of the name. If they are checkers, thats fine, removing them in the final product, if they are there to replace the name, you need to add them different. I put in comments how its solvable. (not sure if its wanted, so i left the solution out of the answer, the code you require is already in this answer, you just gotta put some pieces together)
edit
I just need to add as well (as interaction designer), that requiring a phonenumber isn't smart, especially when it comes to conversion (how often a client will leave a message) . You want people to contact you. Leaving your phonenumber on the web is something "personal" and it will always bring a person in doubt if people ask for phonenumbers. People dont know what will happen to their phonenumber, so they back out on it. State that information is used carefully.
My tip: dont make the phone field a required field. Just the email, name and message.

Categories