How to get dropdown value into .php file - javascript

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'];

Related

Display success message after submit form modal

I have a contact form linked with form-to-email.php to send emails.
What happen is when you click submit it will redirect you to another page (new one) what I would like to have is to show/display the success message within the modal right after clicking the botton.
<div class="modal fade" id="modal-register" tabindex="-1" role="dialog" aria-labelledby="modal-register-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<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="modal-register-label">اشتراك</h4>
</div>
<div class="modal-body">
<form method="post" name="myemailform" action="form-to-email.php">
<div class="row">
<div class="col-xs-12 input-group">
<input type="radio" name="form-busnisstype" value="company" id="company">
<label for="company">شركة</label>
<input type="radio" name="form-busnisstype" value="freelaancer" id="freelancer">
<label for="freelancer">مستقل</label>
</div>
<div class="col-xs-12 input-group">
<input type="text" name="form-name" id="name" placeholder="الاسم الكريم" required="required">
</div>
<div class="col-xs-12 input-group">
<input type="email" name="form-email" id="email" placeholder="البريد الالكتروني" required="required">
</div>
<div class="col-xs-12 input-group">
<input type="tel" pattern="^[0-9]*$" name="form-phone" id="phone" placeholder="05xxxxxxxx" required="required">
</div>
<div class="col-xs-12 input-group">
<select name="form-officetype" id="officetype" required="required">
<option value="" disabled selected hidden="" >اختر مكتبك</option>
<option value="Gold">individual</option>
<option value="Silver">room</option>
<option value="Bronze">meeting</option>
<option value="Basic">orgonization</option>
</select>
</div>
<div class="col-xs-12 input-group">
<select name="form-membership" id="membership" required="required">
<option value="" disabled selected hidden="" >اختر باقتك</option>
<option value="Gold">Gold</option>
<option value="Silver">Silver</option>
<option value="Bronze">Bronze</option>
<option value="Basic">Basic</option>
</select>
</div>
</div>
<div class="row">
<div class="col-xs-12 input-group input-group-icon">
<input placeholder="بداية الاشتراك" type="text" onfocus="(this.type='date')" id="booking" name="form-booking" required="required">
</div>
<div class="col-xs-12 input-group input-group-icon">
<select name="form-person" id="person" required="required">
<option value="" disabled selected hidden="" >كم عدد الاشخاص</option>
<option value="1">1 Person</option>
<option value="2">2 People</option><option value="3">3 People</option><option value="4">4 People</option><option value="5">5 People</option>
</select>
</div>
<textarea id="mep_msg" name="form-message" rows="" Placeholder="Comment" required="required"></textarea>
<input class="send_btn" type="submit" name='submit' value="submit">
</div>
</form>
<script language="JavaScript">
var frmvalidator = new Validator("myemailform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("tel","tel","Please enter a valid email address");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
</div>
</div>
</div>
</div>
<!--Success pop up Starts-->
<div class="modal fade" id="success_msg" role="dialog" tabindex="-1">
<div class="success">
<div class="modal-dialog-success">
<div class="col-xs-12 pade_none">
<button type="button" class="close" onClick="closeConfirm();" data-dismiss="modal">×</button>
<div class="col-xs-12 pade_none">
<h2>Success!</h2>
<p>Your message has been sent.</p>
</div>
<div class="col-xs-12 pad_none">
</div>
</div>
</div>
</div>
</div>
<!--Success pop up ends-->
and the form-to-email.php is the following:
<?php
/* Configuration */
$subject = 'Membership Enquiry'; // Set email subject line here
$mailto = 'email here'; // Email address to send form submission to
/* END Configuration */
$name = $_POST['form-name'];
$visitor_email = $_POST['form-email'];
$message = $_POST['form-message'];
$phone = $_POST['form-phone'];
$busnisstype = $_POST['form-busnisstype'];
$officetype = $_POST['form-officetype'];
$membership = $_POST['form-membership'];
$person = $_POST['form-person'];
$booking = $_POST['form-booking'];
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>الاسم</b>: $name<br>
<b>الايميل</b>: $visitor_email<br>
<b>رقم الجوال</b>: $phone<br>
<b>نوع المشأة</b>: $busnisstype<br>
<b>المكتب المرغوب</b>: $officetype<br>
<b>العضوية</b>: $membership<br>
<b>عدد الاشخاص</b>: $person<br>
<b>التاريخ المتوقع لبدء الاشتراك</b>: $booking<br>
<p>ملاحضات اخرى: <b>$message</b></p>
";
$headers = "From: $name <$visitor_email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
header('Location: thank-you.html');
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
You're redirecting to thank-you.html. Add there the code (with the success message) and if you want it to be a modal just add the modal code:
<!--Success pop up Starts-->
<div class="modal fade" id="success_msg" role="dialog" tabindex="-1">
<div class="success">
<div class="modal-dialog-success">
<div class="col-xs-12 pade_none">
<button type="button" class="close" onClick="closeConfirm();" data-dismiss="modal">×</button>
<div class="col-xs-12 pade_none">
<h2>Success!</h2>
<p>Your message has been sent.</p>
</div>
<div class="col-xs-12 pad_none">
</div>
</div>
</div>
</div>
</div>
<!--Success pop up ends-->
And launch a javascript when entering:
<body onload="myOnloadFunc();">
Your function should show modal:
function myOnloadFunc() {
$('#success_msg').modal('show');
}
You do two things either use AJAX to send request to form-to-email.php script or create hidden iframe with id="email" name="email" and use target="email" in form tag, it will open your php script in iframe and execute it but it will not redirect to that page, then you can use
document.getElementById('email').addEventListener('load', function() {
alert('Email Send Successfully');
});
instead of alert you can add toaster (green bar) to your modal.
PHP CODE
<?php session_start();
include('config/connect_database.php');
$Username = '';
if(isset($_POST['Login'])) {
$Username = mysqli_real_escape_string($conn, $_POST['Username']);
$Password = mysqli_real_escape_string($conn, $_POST['Password']);
$sql = "SELECT Username, Password, Authority FROM user WHERE Username LIKE '$Username' AND Status LIKE 'Active'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
$username = mysqli_fetch_assoc($result);
mysqli_free_result($result);
mysqli_close($conn);
if(($Username === $username['Username']) && (password_verify($Password, $username['Password']))) {
$_SESSION['Username'] = $_POST['Username'];
$_SESSION['Authority'] = $username['Authority'];
} else {
echo "<script>alert('Invalid Username or Password');</script>";
}
} else {
echo "<script>alert('Invalid Username or Password');</script>";
}
}
?>
HTML CODE
<!DOCTYPE html>
<html>
<head>
<title>Management System</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
<?php if(isset($_SESSION['username'])){?>$('#modalNotification').modal();<?php } ?>
$('div.modal button').click(function(){ location.href='home.php'; });
});
</script>
</head>
<body>
<nav>
<a class="navbar-brand" href="#">
<img src="Source/pms_logo_blue.png" alt="Logo" style="width:50px;">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="register.php">Register</a>
</li>
</ul>
</div>
</nav>
<div class="modal fade" id="modalNotification" tabindex="-1" role="dialog" aria-labelledby="modalNotificationTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalNotificationTitle">NOTIFICATION</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>CONTENT</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-center py-5">
<div class="col" style="max-width: 400px;">
<h3 style="text-align: center;">Flinken Production Management System</h3>
</div>
</div>
<div class="row justify-content-center">
<div class="col" style="max-width:400px;">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div class="form-group">
<label>Enter Email</label>
<input type="email" name="Username" value="<?php echo htmlspecialchars($Username); ?>" class="form-control" required>
</div>
<div class="form-group">
<label>Enter Passsword</label>
<input type="password" name="Password" class="form-control" required>
</div>
<div class="form-group">
<button type="submit" name="Login" value="True" class="btn btn-primary btn-block">Login</button>
</div>
</form>
</div>
</div>
</div>
<footer class="section">
<div class="text py-5" style="text-align: center">Copyright </div>
</footer>
</body>
</html>

How do I creat a jquery form validator

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.

How to write success message of form in bootstrap modal?

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;
}

JQuery form submit do not validate fields

I have used Parsley.js for form validation. I am submitting via a JQuery, so the page will not get refreshed. However when I am using the Javascript code for for submitting, I noticed the form validations are not taking place anymore. Previously, when I was not using Javascript, the form validation has taken place.
This is my html code and I used parsley.js here .
<form id="contact-form" action="xxx.php" method="POST" data-parsley-validate>
<div class="contact-form-loader"></div>
<fieldset>
<label class="name">
<input type="text" id="nme" name="name" placeholder="Name:" value=""
data-constraints="#Required #JustLetters" data-required="true"/>
</label>
<label class="email">
<input type="text" name="email" placeholder="Email:" value=""
data-constraints="#Required #Email" data-parsley-trigger="change" data-required="true"/>
</label>
<label class="phone">
<input type="text" name="phone" placeholder="Phone:" value=""
data-constraints="#JustNumbers" data-required="true"/>
</label>
<label class="message">
<textarea name="message"
data-parsley-trigger="keyup" placeholder="Message :" data-parsley-minlength="15"
data-parsley-validation-threshold="10" data-required="true"
data-parsley-minlength-message = "You need to enter at least a 20 character comment ! ..">
</textarea>
</label>
<div class="btn-wrapper">
<a class="btn_2 text_3 color_7" href="#" data-type="reset">Clear</a>
<!-- <a class="btn_2 text_3 color_7" href="#" data-type="submit">Send</a>-->
<input id="sub" type="submit" name="submit" class="btn_2 text_3 color_7" value="Send"/>
</div>
</fieldset>
<div class="modal fade response-message">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
You message has been sent! We will be in touch soon.
</div>
</div>
</div>
</div>
</form>
And this is my java script ,
<script type="text/javascript">
$("#sub").click(function() {
var url = "xxx.php";
$.ajax({
type: "POST",
url: url,
data: $("#contact-form").serialize(),
success: function(data)
{
alert("Message Sent !");
}
});
return false;
});
</script>
And this is the xxx.php I've used to send e-mails .(This is worked in my server)
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$to='nirodha1500#gmail.com';
$subject='Contact Form Message';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .='From : '.$email."r\n".
'Reply-To : '.$email."r\n".
'X-Mailer: PHP/' . phpversion();
$sent=mail($to,$subject,$message,$headers);
if(!$sent){
echo "There are problems in sending mails <br>";
}else{
echo "End mail sending";
}
echo "Sent mail";
?>
Does anyone have a possible idea ?
The correct way to use ajax to submit a form is to do so on('submit', ...), not on click.
Also, make sure that you bind your submit event after parsley does.
You could also use parsley and bind form:success instead, if you prefer:
$('#contact-form').parsley().on('form:success', ...)

Form Redirect Success/Fail page

I have tried to make my form redirect to a success or fail page. I have searched all through the internet, looking at normal form redirects and even javascript onClick redirect's. Can someone help me add with adding a redirect:
HTML:
<!-- ///////////////////////////////////////////////////////////////////////////////// -->
<!-- CONTACT FORM -->
<div class="col-lg-6">
<h1>CONTACT</h1>
<h3 class="service_h3">Say Hello! Ask something?</h3>
<form action="submit_contact.php" id="contactForm">
<fieldset>
<div id="result"></div>
<!-- ///////////////////////////////////////////////////////////////////////////////// -->
<!-- NAME FIELD -->
<div class="form-item">
<label for="name">
<input type="text" name="name" id="name" placeholder="Enter Your Name" required/>
</label>
</div>
<!-- ///////////////////////////////////////////////////////////////////////////////// -->
<!-- EMAIL FIELD -->
<div class="form-item">
<label for="email">
<input type="email" name="email" id="email" placeholder="Enter Your Email" required/>
</label>
</div>
<!-- ///////////////////////////////////////////////////////////////////////////////// -->
<!-- MESSAGE FIELD -->
<div class="form-item">
<label for="message">
<textarea name="message" id="message" placeholder="Your Message" required></textarea>
</label>
</div>
<!-- ///////////////////////////////////////////////////////////////////////////////// -->
<!-- SUBMIT BUTTON -->
<div class="form-item">
<button name="submit" class="submit_btn" action="submit_contact.php" window.open("Done") type="submit">Submit</button>
</div>
</fieldset>
</form>
</div>
PHP:
<?php
/* Subject and Email Variables*/
$emailSubject = 'Contact Form Submission';
$webMaster = 'no-reply#*Hidden*.com';
/* Gathering Data Variables */
$nameField = $_POST['name'];
$emailField = $_POST['email'];
$messageField = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$hostaddress = gethostbyaddr($ip);
$browser = $_SERVER['HTTP_USER_AGENT'];
$referred = $_SERVER['HTTP_REFERER'];
$body = <<<EOD
<br><img src="*Hidden*"> <br>GoAerox! Network - Contact Form Submission<hr><br>
<strong>Name:</strong> $nameField <br>
<strong>Email:</strong> $emailField <br>
<strong>Message:</strong> $messageField <br><br>
<hr><br><strong>User Details</strong><br>
<strong>IP Address:</strong> $ip <br>
<strong>Host address:</strong> $hostaddress <br>
<strong>Browser:</strong> $browser <br>
<strong>Referred:</strong> $referred <br>
EOD;
$headers = "From: $emailField\r\n";
$headers .= "Content-type: text/html\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);
/* Results rendered as HTML */
$theResults = <<<EOD
<html>
**RESULT PAGE**
</html>
EOD;
echo "$theResults";
?>
Please give an answer that is easily read by a amatuer PHP coder. Note: I am happy for this to redirect to a page or popup on the actual contact page. As long as the user can see that the form has been submitted without error.
You can use the following code to redirect to your success or fail page
<?php
$emailSubject = 'Contact Form Submission';
$webMaster = 'no-reply#*Hidden*.com';
$nameField = $_POST['name'];
$emailField = $_POST['email'];
$messageField = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$hostaddress = gethostbyaddr($ip);
$browser = $_SERVER['HTTP_USER_AGENT'];
$referred = $_SERVER['HTTP_REFERER'];
$body = <<<EOD
<br><img src="*Hidden*"> <br>GoAerox! Network - Contact Form Submission<hr><br>
<strong>Name:</strong> $nameField <br>
<strong>Email:</strong> $emailField <br>
<strong>Message:</strong> $messageField <br><br>
<hr><br><strong>User Details</strong><br>
<strong>IP Address:</strong> $ip <br>
<strong>Host address:</strong> $hostaddress <br>
<strong>Browser:</strong> $browser <br>
<strong>Referred:</strong> $referred <br>
EOD;
$headers = "From: $emailField\r\n";
$headers .= "Content-type: text/html\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);
header('location:success.php');
?>
$redirecturl ="Your thank you page url"
header('Location: '.$redirecturl);
Use header function to redirect to another page.
Place this function after your mail function completed.

Categories

Resources