SOLVED
Ok, I solved the problem with AJAX but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. The working code is by CodexWorld. I hope I help someone who is helpless.
I am searching for solution all day but I don't get relevant solution anywhere. Other similar questions here are old, maybe there are fresh solution.
So I am using Bootstrap the first time (files are on the themes of Wordpress). I started to build a contact form in Modal and if I hit submit the window closes, I get the e-mail, but the success-message only shows if I reopen it. I tried every solution I found on internet.
I am not familiar with javascript and jquery, I don't know how to use it.
In the footer I implemented:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
In index there is the form with Modal:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal clearfix" id="contact-form" name="contact" role="form" method="post" action="index.php">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Küldj egy üzenetet</h4>
</div>
<div class="modal-body">
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Itt landol</label>
<div class="col-sm-10">
<input class="form-control" id="disabledInput" type="text" placeholder="hello#kanizsaipatricia.hu" disabled>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Név</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="Minta János" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="valaki#email.hu" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Üzenet</label>
<div class="col-sm-10">
<textarea class="form-control" placeholder="Ide írd az üzenetet" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
</div>
<?php echo $result; ?>
<div class="modal-footer">
<button type="button" class="btn btn-cancel hvr-fade" data-dismiss="modal">Mégsem</button>
<input type="submit" id="submit" name="submit" data-toggle="modal" data-target="#resultModal" value="Elküldöm" class="btn btn-info hvr-wobble-horizontal">
</div>
</pop:form>
</div>
</div>
The php code behind the form:
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Üzenetküldő űrlap';
$to = 'hello#kanizsaipatricia.hu';
$subject = 'Új üzenet formon keresztül';
$body = "Feladó: $name\n E-Mail: $email\n Üzenet:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Kérlek, add meg a neved!';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Nem érvényes e-mail cím!';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Nem írtál üzenetet.';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success noshadow">Elküldve.</div>';
} else {
$result='<div class="alert alert-danger noshadow">Sajnálom, hiba lépett fel az üzenet küldése közben. Próbáld újra!</div>';
}
}
}
I'm open minded for any solution in any language! Please help!
Ok, I solved the problem with ajax but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. Thanks to CodexWorld.
Bootstrap & jQuery Library
Bootstrap is used to create modal popup and design HTMl form, include the bootstrap and jQuery library first.
<!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Bootstrap Modal Popup Form
<!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
Open Contact Form
</button>
<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JavaScript Code: Validate and Submit Form
<script>
function submitContactForm(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'submit_form.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Send Contact Request Email (submit_form.php)
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'admin#example.com';
$subject= 'Contact Request Submitted';
$htmlContent = '
<h4>Contact request has submitted at CodexWorld, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Message:</th><td>'.$message.'</td>
</tr>
</table>';
// 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: CodexWorld<sender#example.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
Related
I am trying to create a dynamic website using php. The site is uploaded to a free domain this is my first real world project so I want to put in as best as I can. I created a modal, in it there is a form and I want this from to validate and without refreshing the page. but I don't know why my mail() is not working please can someone tell me what I am doing wrong.
This is my fixed form inside the modal:
<div class="modal fade" id="myModal" tabindex="-1" role="form" aria-labelledby="#modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title " id="modalLabel">Send
<?php echo
$brandName; ?> a message</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="thumbnail">
<form action="contact_process.php" method="POST" role="form" autocomplete="off" class="form-container">
<small>
<i class="text-center
text-danger">all fields are required</i>
</small>
<div class="form-group has-danger">
<label class="sr-only" for="name">Name
</label>
<input type="text" name="name" placeholder="Your Name" class="form-control" id="mail-name" tabindex="1">
</div>
<div class="form-group has-danger">
<label class="sr-only" for="email">Email
</label>
<input type="email" name="email" placeholder="Your E-mail" class="form-control" id="mail-email" tabindex="2">
</div>
<div class="form-group has-danger">
<label for="tel" class="sr-only">Tell
no.
</label>
<input type="text" name="phone" placeholder="Your Phone Number" class="form-control" id="mail-
phone" tabindex="3">
</div>
<div class="form-group has-danger">
<label for="message" class="sr-only">
</label>
<textarea class="form-control
form-textarea" placeholder="Message" rows="5" spellcheck="true" name="message" id="mail-message" tabindex="4"></textarea>
</div>
<input type="button" class="btn
btn-danger" data-dismiss="modal" aria-label="Close" value="Cancel" tabindex="5">
<input id="mail-submit" type="submit" class="btn btn-primary" value="Send Message" name="submit" data- submit="...Sending" tabindex="6">
<p class="form-msg"></p>
</form>
</div>
<!--END thumbnail-->
</div>
<!--END col-->
</div>
<!--END row-->
</div>
<!--modal-body-->
</div>
<!--modal-content-->
</div>
<!--modal-dialog-->
</div>
<!---modal-->
This is the php form validation in my includes folder:
<pre>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorPhone = false;
if (empty($name) || empty($email) || empty($phone) || empty($message)) {
echo "<span class='err'>Fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='err'>Invalid email please make sure you enter a
valid email address!</span>";
$errorEmail = true;
}
elseif (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?
\d{3}[\s-]?\d{4}$/i",$phone)) {
echo "<span class='err'>Please enter only a valid phone number!
</span>";
$errorPhone = true;
}
else{
// add resipeants
$to = "danjumashiwaju#gmail.com";
// create subject
$subject = "$name sent you a message from www.djshumzy.com";
// construct a message
$msg = "Name: $name\r\n";
$msg .= "Email: $email\r\n";
$msg .= "Tell: $phone\r\n";
$msg .= "Message: \r\n$message";
$msg = wordwrap($meg, 70);
//set mail header
$headers = "MINE-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=1so-8859-1\r\n";
$headers .= "From: $name <$email>\r\n";
$headers .= "X-priority: 1\r\n";
$headers .= "X-MSMail-priority: High1\r\n\r\n";
mail( $to, $subject, $msg, $headers);
} if (mail === 1) {
echo "<span class='suc'>Thank You!...Your Message has been Sent !
</span>";
}
}
?>
<script>
$("#mail-name, #mail-email, #mail-phone,
#mail-message").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorEmail = "<?php echo $errorEmail; ?>";
var errorPhone = "<?php echo $errorPhone; ?>";
if (errorEmpty == true) {
$("#mail-name, #mail-email, #mail-phone,
#mail-message").addClass("input-error");
}
if (errorEmail == true) {
$("#mail-email").addClass("input-error");
}
if (errorPhone == true) {
$("#mail-phone").addClass("input-error");
}
if (errorEmpty == false && errorEmail == false && errorPhone == false) {
$("#mail-name, #mail-email, #mail-phone, #mail-message").val("");
}
</script>
</pre>
Here is my jquery validation(.js)
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-msg").load("includes/contact_process.php", {
name: name,
email: email,
phone: phone,
message: message,
submit: submit
});
});
});// END FORM VALIDATING
Please what do I have to do to make this from submit to emails and validate at the same time.
Thus the form validates but it does not send the email and just gives an error message instead.
Use https://jqueryvalidation.org/
$( "#myform" ).validate({
rules: {
field: {
required: true
},
email: {
required: true,
email: true
}
},
messages: {
field: "Please Enter Your Name",
email: "Please Enter Your Email Address"
}
});
<link href="https://jqueryvalidation.org/files/demo/site-demos.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="myform">
<label for="field">Enter Name : </label>
<input type="text" class="left" id="field" name="field">
<br/>
<label for="email">Email Address: </label>
<input type="text" id="email" name="email">
<br/>
<input type="submit" value="Validate!">
</form>
This jQuery plugin makes simple clientside form validation easy.
I tried to make a contact form within a bootstrap modal.
An alert should show up right after submitting the form in the modal.
It is working fine on my site which I use for testing.
But when I integrate the code in my main site the alert is shown as text in a new window. Same code. Different response. What could cause this behavior?
HTML:
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-12">
<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 firstname *" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<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 *" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-->
PHP:
<?php
// configure
$from = 'noreplay#xy.de';
$sendTo = 'webmaster#xy.de';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $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['message'];
}
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();
}
}
});
return false;
}
})
});
The action parameter in form tag action="contact.php" is forcing the page to refresh try using this as form tag :-
<form id="contact-form">
and change $(this).serialize() in your ajax post code to :-
$('#contact-form').serialize()
Form:
<form class="form-horizontal" data-toggle="validator" method="post" role="form" id="enquiryForm">
<div class="form-group">
<label class="col-lg-2 control-label">Full Name :</label>
<div class="col-lg-8">
<input type="text" name="fname" class="form-control" id="inputFirstName" data-error="Please fill out this field." placeholder="Full Name" required>
<div class="help-block with-errors"></div>
</div>
<button type="button" class="btn btn-info" id="existName">Next</button>
</div>
</form>
AJAX:
$('#existName').click(function(){
var fname = $('#inputFirstName').val();
var datas = "fname="+fname;
console.log(datas);
$.ajax({
url : "exist.php",
data : datas,
method : "POST"
}).done(function(exist){
console.log(exist);
$('#existNameModal').html(exist);
})
})
PHP:
<?php
session_start();
$companydata = $_SESSION['company'];
$idCompany = $companydata['id'];
$fnameCompany = $companydata['fname'];
$lnameCompany = $companydata['lname'];
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Latest compiled and minified CSS -->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "gym";
$conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die ("could not connect");
if($_POST){
$existName = $_POST['fname'];
$sql = "SELECT count(fname) from enquiry where fname = '$existName' AND cmpId = '$idCompany'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
print_r($row);
/*exit;*/
if(($row)>0) {
$modal = '
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>';
echo $modal;
}
}
?>
</body>
</html>
Modal HTML
<!-- Name exist Modal -->
<div id="existNameModal" class="modal fade" role="dialog">
</div>
I am trying to get this Modal display when count(fname) in DB is more than 0. I tried everything but nothing worked.
From with Modal (form and modal both will be on same page)
<form class="form-horizontal" data-toggle="validator" method="post" role="form" id="enquiryForm">
<div class="form-group">
<label class="col-lg-2 control-label">Full Name :</label>
<div class="col-lg-8">
<input type="text" name="fname" class="form-control" id="inputFirstName" data-error="Please fill out this field." placeholder="Full Name" required>
<div class="help-block with-errors"></div>
</div>
<button type="button" class="btn btn-info" id="existName">Next</button>
</div>
</form>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="existNameModal"></div> //this is where message will show
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In Ajax, you are using click function, better do it with change function on input and check the record if exist like
$('#inputFirstName').change(function(){
var fname = $(this).val();
//rest of code
});
The Ajax with click function
$('#existName').click(function(){
var fname = $('#inputFirstName').val();
var datas = "fname="+fname;
console.log(datas);
$.ajax({
url : "exist.php",
data : datas,
method : "POST"
})
});
Now to show modal and message if record exist
.done(function(exist){
console.log(exist);
if(exist.status=='error') {
$('#myModal').modal('show');
$('#existNameModal').html(exist.message);
}
});
The php exist.php
<?php
header('Content-Type: application/json');
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "gym";
$conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die ("could not connect");
if($_POST['fname']){
$existName = $_POST['fname']; //escape the string
$sql = "SELECT count(fname) from enquiry where fname = '$existName' AND cmpId = '$idCompany'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
//print_r($row);
if(($row)>0) {
$response['status'] = "error";
$response['message'] = "<div class='alert alert-danger'>Record Already Exist</div>";
}
echo json_encode($response);
}
?>
Hullo. I am trying to make a modal appear on my website that will let people who visit send messages to an email i have designated. I am completely new to coding and have spent many hours trawling these forums for help. I followed this tutorial: https://bootstrapbay.com/blog/working-bootstrap-contact-form/.
This is my html:
<div class ="modal fade" id="contact" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" role="form" method="post" action="contact.php">
<div class="modal-header">
<h4> Contact </h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="nameinput" type="text" class="form-control" id="contact-name" placeholder="First & Last Name">
<?php echo "<p class='text-danger'> $errName </p>";?>
</div>
</div>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="emailinput" type="email" class="form-control" id="contact-email" placeholder="example#gmail.com">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name = "messageinput" class="form-control" id="contact-message" rows="4"></textarea>
<?php echo "<p class='text-danger'>$errMsg</p>";?>
</div>
</div>
</div>
<div class="modal-body">
<div class="form-group">
<label for="human" class="col-sm-2 control-label"> 2 + 3 ? </label>
<div class = "col-sm-10">
<input type = "text" class="form-control" id="human" name="human" placeholder="Type your answer here">
<?php echo "<p class='text-danger'>$errHuman</p>";?>
</div>
</div>
</div>
<div class="modal-body">
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<!-- will be used to display an alert to the user -->
</div>
</div>
</div>
<div class="modal-footer">
<div class = "form-group">
<div class="col-sm-10 col-sm-offset-2">
<a class="btn btn-default" data-dismiss="modal">Close</a>
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
This is my php:
<?php
$errName='' ;
$errEmail='';
$errMsg='';
$result='';
$errHuman='';
//have to define variables outside of if statements, even if you just set them to null or ''//
if(isset($_POST["submit"])) {
$name = $_POST['nameinput'];
$email = $_POST['emailinput'];
$message = $_POST['messageinput'];
//$human = intval($_POST['human']);
$from = 'From: $name';
$to = 'danroebuck1994test#gmail.com';
$subject = 'Message from Contact Form';
$body ="From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['nameinput']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['emailinput'] || !filter_var($_POST['emailinput'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['messageinput']) {
$errMsg = 'Please enter your message';
}
//If there are no errors, send the email
if (!$errName && !$errEmail && !$errMsg) {
if (mail ($to, $subject, $body, $from)) {
echo "<script type='text/javascript'>alert('Email sent successfully')</script>";
} else {
echo "<script type='text/javascript'>alert ('An error occurred, the email has not been sent. Please try again later.')</script>";
}
//}
}
?>
The first trouble I am having is that when I open up the modal by pressing the contact button, the red text is not displaying below the fields to ask for the required inputs.
The second issue is that whenever I refresh the page, the previous email I set up in the form is sent lol, with the alert popping up saying 'your email has been sent successfully'. This seemed very weird to me as I thought using the if(isset($_POST["submit"])) would mean it would only be sent if the submit button was clicked.
I ask for any assistance possible. I did search these forums for a solution and I found this: PHP email form sends email everytime page is refreshed. However I did not find it helpful to me. As this was 6 hours ago and I have now made no progress I figured it would be reasonable to ask. Thankyou friends.
I need to get selected dropdown value into my .php file, which is actually send mail file.
When i select one of 6 options from dropdown, i want selected option to be included into the mail as the "subject" of the email.
Here is my HTML code
<span class="custom-dropdown big">
<select id="mounth" name="mounth">
<option value="default">-- Domain name --</option>
<option value="value1" rel="icon-temperature">value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
<option value="value5">value5</option>
<option value="value6">value6</option>
</select>
<input type="hidden" id="changeme" name="changeme" />
</span>
POPUP EMAIL FORM
<div class="modal fade" id="popup-moda">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span id="spanhide" aria-hidden="true">×</span></button>
<h4 class="modal-title">Contact Us</h4>
</div>
<form action="" method="post" name="form" id="forms">
<div class="modal-body">
<div id="domain" name="domain"></div>
<input required id="name" name="name" placeholder="Name" type="text">
<input required id="email" name="email" placeholder="Email" type="text">
<textarea id="msg" name="msg" placeholder="Message"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send</button>
<div id="success" style="color: blue;"></div>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Here is my JS code which actually displays selected option, but only as text before sending email.
$(document).ready(function(){
$('.popup').click(function(e){
e.preventDefault();
$('#domain').html('<b>' + $('#mounth').val() + '</b>');
$('#popup-moda').modal('show');
return false;
});
});
My PHP file
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['msg'];
$to = 'example#example.com';
$subject = 'New Customer Enquiry';
$msg = <<<EMAIL
Subject: $subject
Message: $msg
From: $name
Email: $email
EMAIL;
$headers = 'From:' . $email;
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
mail($to, $subject, $msg, $headers); mail.
echo "Thank you for your email! We will reply as soon as possible.";
}
else
{
echo "Invalid Email, please provide a correct email address.";
}
?>
Thank you guys. Any input is appreciated!
Put the select inside your form so the selected value is sent to server along with the rest of form parameters.
<form action="" method="post" name="form" id="forms">
<!-- ... -->
<select id="mounth" name="mounth">
<!-- options -->
</select>
<!-- ... -->
</form>
Then in your php file:
$subject = $_POST['mounth'];
And then use it in the subject.
EDIT:
Then you can add a hidden input to your form with that name and add the dropdown's value to it upon selection:
<form action="" method="post" name="form" id="forms">
<!-- form stuff -->
<input type="hidden" id="hiddenMounth" name="mounth" value="" />
</form>
And then listen to select's onchange:
$('#mounth').on('change', function() {
$('#hiddenMounth').val($(this).val());
});
And then in your php:
$subject = $_POST['mounth'];