This is my Modal layout:
<div class="modal fade" id="myContact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Send me a message</h3>
<div id="thanks"></div>
</div>
<div class="modal-body">
<form class="contact" name="contact">
<input type="text" name="name" class="form-control" placeholder="Your Name"><br>
<input type="email" name="email" class="form-control" placeholder="Your E-mail"><br>
<textarea name="message" class="form-control" placeholder="Enter a Message"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
</div>
And this is the Jquery Script:
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //process to mail
data: $('form.contact').serialize(),
success: function(msg){
$("#myContact").modal('hide'); //hide popup
$("#thanks").html(msg) //hide button and show thank you
},
error: function(){
alert("failure");
}
});
});
And the PHP process.php:
<?php
//add the recipient's address here
$myemail = 'test#mail.com';
//grab named inputs from html then post to #thanks
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
echo "<class=\"alert alert-success\" >Your message has been !";
//generate email and send!
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}
?>
First of all, Hello to All i`m new here....
I have a question.. how can I do when i push Send my Modal to hide (but whit delay to see the alert-success message ) and to be reset...
now is working and send my email but does not close and reset..
Thx Elod !!
on success you can use reset to reset the form in the modal
use an id for the form like my_Contact
$('#my_contact').reset(); //to reset the form
delay the modal hide can use setTimeout
setTimeout(function() { $('#myContact').modal('hide'); }, 3000);
Related
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;
});
I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php
So I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine when placed on a page, however when I place it inside a bootstrap popup modal, the validator doesn't work. If all fields are empty and submit button hit, it will say 'message sent' even though it did not send, and if you fill in the fields it will still send and give success message also.
Also, if I hit the button to open modal as soon as page loads but before the script has loaded, it will work, so it's obviously because the modal is not visible when the validator script loads, so it misses it.
If anyone has some answers it would be super helpful as I'm pretty new to PHP and JS!
Here is my modal HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<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 class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<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 class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>
This is my PHP file
<?php
// configure
$from = '<mail#myemail.net>';
$sendTo = 'Demo contact form <mail#myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => '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';
$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail#myemail.net' . "\r\n" ;
// 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($email, $subject2, $msg, $headers) && 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'];
}
?>
And 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;
}
})
});
Put your ajax call inside the validation process and use submitHandler.
This answer by #Sparky might save your day https://stackoverflow.com/a/15625824/6952155
Please refer to this and edit to suit in your code.
$(document).ready(function () {
$("#contactform").validate({
ignore: ":hidden",
rules: {
name: {
required: true,
minlength: 3
},
cognome: {
required: true,
minlength: 3
},
subject: {
required: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function (form) {
alert('valid form submission'); // for demo
$.ajax({
type: "POST",
url: "formfiles/submit.php",
data: $(form).serialize(),
success: function () {
$(form).html("<div id='message'></div>");
$('#message').html("<h2>Your request is on the way!</h2>")
.append("<p>someone</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/ok.png' />");
});
}
});
return false; // required to block normal submit since you used ajax
}
});
});
Ondrej here, author of the tutorial on Bootstrapious.
I have just found out that there was an error in Bootstrap validator and it was not working correctly in combination with the Bootstrap modal.
The solution is downloading the latest version from https://github.com/1000hz/bootstrap-validator, currently 0.11.5.
Best,
Ondrej
I've built this page using a button to trigger a modal that has a contact form.
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#stayInformed">Stay Informed</button>
I'm trying to submit that form to the php at the top of the page to send myself an email. However, the php is not sending the email nor is it displaying the echos.
<?php
$myemail = 'user#email.com';
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$company = strip_tags($_POST['company']);
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<stong>Name:</strong> ".$name."<br>";
echo "<stong>Email:</strong> ".$email."<br>";
echo "<stong>Company:</strong> ".$company."<br>";
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Company \n $company";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}?>
There is JavaScript at the bottom which should trigger the form POST.
<script>
$(document).ready(function () {
$('form#contact').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "index.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#stayInformed").modal('hide');
alert(document.getElementById("name").value + " " + document.getElementById("email").value + " " + document.getElementById("company").value);
},
error: function(){
alert("failure");
}
});
});
});
</script>
The button is triggering the modal correctly and the JavaScript seems to be functioning correctly. It closes the modal on submit and if I change the php pointer to something that doesn't exist it throws the error.
Entire page with modal posted below:
<?php
$myemail = 'user#email.com';
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$company = strip_tags($_POST['company']);
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<stong>Name:</strong> ".$name."<br>";
echo "<stong>Email:</strong> ".$email."<br>";
echo "<stong>Company:</strong> ".$company."<br>";
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Company \n $company";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Modal Form Test</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<p><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#stayInformed">Stay Informed</button>
</p>
</div> <!-- /container -->
</div> <!-- /jumbotron -->
<!-- stayInformed Modal -->
<div class="modal fade" id="stayInformed" tabindex="-1" role="dialog" aria-labelledby="stayInformed">
<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>
<h4 class="modal-title">Stay Informed!</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="contact" role="form" method="post" action="index.php">
<fieldset>
<legend>Register Below</legend>
<div class="form-group">
<label for="textArea" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="name" placeholder="First Last"></input>
</div>
</div>
<div class="form-group">
<label for="textArea" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="email" placeholder="name#company.com">
</div>
</div>
<div class="form-group">
<label for="textArea" class="col-lg-2 control-label">Company</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="company" placeholder="Company"></input>
</div>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-primary" form="contact"></input>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- JavaScript for modal form -->
<script>
$(document).ready(function () {
$('form#contact').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "index.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#stayInformed").modal('hide');
alert(document.getElementById("name").value + " " + document.getElementById("email").value + " " + document.getElementById("company").value);
},
error: function(){
alert("failure");
}
});
});
});
</script>
</body>
</html>
Edit: I changed javascript a bit ad the value of some ids to get rid of repeats. Still not working. I can now see the values in my success alert but it still doesn't appear that the PHP is executing.
Edit 2: After some troubleshooting it appears that there are no variables being sent to the php in $_POST. I'm not sure why...
Just change this:
$("input#submit").click(function(){
// stuff
});
By this:
$('form#stayInformed').on('submit', function(event) {
event.preventDefault();
// stuff
});
Resume:
Not listening click on button, you must to listen the form submit event. the preventDefault() method disables default action, that is submit the form without ajax. With this code, all runs ok.
Next time, please, try it yourself and search how it mades in google. This is basic javascript premises.
Good luck
EDIT
Note that the ID #stayInformed is duplicated in a DIV and in the FORM. It's very bad practice. Please, be sure that the IDs aren't duplicated in the html code.
I changed the JavaScript to code to:
<script>
$(document).ready(function () {
$('#contact').submit(function(event) {
var formData = {
'name' : $('input[id=name]').val(),
'email' : $('input[id=email]').val(),
'company' : $('input[id=company]').val()
};
event.preventDefault();
$.ajax({
type: "post",
url: "index.php",
data: formData,
success: function(msg){
$("#stayInformed").modal('hide');
},
error: function(){
alert("form post failed");
}
});
});
});
</script>
This works.
Getting a 500 Internal Server error on the client side when trying to test with phpmailer.
Based on my knowledge, it's throwing the error due to a misplaced or nonexistent file, but the file is actually there.
Here's a screenshot of the file structure for the site and for the includes file
PHP
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
// $email = $_POST['email'] ;
// $message = $_POST['message'] ;
// When we unzipped PHPMailer, it unzipped to
// based on where this php file sites, i gave it the following path.
// But also tried, '../includes/phpmailer.class.phpmailer.php'
// and also tried, 'phpmailer.class.phpmailer.php'
require_once("includes/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587;
$mail->Username = "patrick.johnson9#gmail.com";
$mail->Password = "corner09";
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddAddress("im#pbj.me","First Last")
$mail->Subject = "PHPMailer Test Subject via smtp (Gmail), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
JAVASCRIPT
// Form submission
$("#form-apply").submit(function(e){
e.preventDefault();
// get the form data
var formData = {
"name": $("input[name='name']").val(),
"email": $("input[name='email']").val(),
"message": $("input[name='message']").val(),
// "upload": $("textarea[name='upload']").val()
};
console.log(formData);
$.ajax({
type: "POST", //define the type of HTTP verb we want to use
url: "../includes/form-apply.php",
data: formData, //our data object
dataType: "json",
encode: true
}).done(function(data){ //using the done promise callback
// log the data to the console so we can see it
console.log(data);
if(! data.success){
if (data.errors.name){
$("#name").parent().addClass("has-error");
$(".name-group").append("<div class='help-block'>" + data.errors.name + "</div>");
// $("#name").attr("placeholder", data.errors.name);
}
if(data.errors.email){
$("#email").parent().addClass("has-error");
$(".email-group").append("<div class='help-block'>" + data.errors.email + "</div>");
}
if(data.errors.subject){
$("#subject").parent().addClass("has-error");
$(".subject-group").append("<div class='help-block'>" + data.errors.subject + "</div>");
}
if(data.errors.message){
$("#message").parent().addClass("has-error");
$(".message-group").append("<div class='help-block'>" + data.errors.message + "</div>");
}
} else {
$(".form-apply").prepend("<div class='alert alert-success'>" + data.message + "</div>")
$("input, textarea").val("");
}
}).fail(function(data){
$("#form-apply").prepend("<div class='alert alert-danger'>" + data.errors + "</div>");
console.log(data.errors);
});
});
HTML NOTE THIS MODULE IS A PHP INCLUDE CALLED 'CAREER-MODAL.PHP WHICH EXISTS IN THE 'INCLUDES' DIRECTORY.
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<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 center" id="myModalLabel">Career Application</h4>
</div>
<div class="modal-body">
<form id="form-apply" role="form" method="POST" action="includes/form-apply.php">
<div class="row">
<div class="col-md-6">
<div class="form-group name-group">
<label for="name">Full Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Full Name" tabindex="1" required="required">
</div>
</div>
<div class="col-md-6">
<div class="form-group email-group">
<label for="name">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email Address" tabindex="2" required="required">
</div>
</div>
</div>
<div class="form-group .message-group">
<label for="name">Summary of Background</label>
<textarea name="message" id="message" class="form-control" placeholder="Message" tabindex="3" required="required"></textarea>
</div>
<div class="form-group">
<label for="name">Upload Resume</label>
<input type="file" name="upload" id="upload" class="form-control" placeholder="No File Chosen" tabindex="4">
</div>
<div class="row center">
<button class="btn btn-secondary" tabindex="4">submit</button>
</div>
</form>
</div>
</div>
</div>
</div>