I am using the malsup jquery form plugin to email a form via PHP, my form is in a bootstrap modal.
Everything seems to work fine, I receive success message however the email never shows up. It has something to do with my Ajax because the form works if I dont use AJAX, however, it then sends the user to the PHP url which is why i decided to use the plugin.
I have tried the ajaxForm and ajaxSubmit functions from malsup but with no success, the email just never shows up.
As a note, I am using another form (different name and id) and another AJAX and PHP call, but they work fine. They are completely separate files with different names, etc...
Plugin
http://jquery.malsup.com/form/#getting-started
Live website (select Contact Me button)
http://www.sitesbymiller.com
HTML
<form class="contactModalForm" id="contactModalForm" action="modalForm.php" method="post">
<div class="form-group">
<label for="contactName">Name*</label>
<input type="text" class="form-control" name="modalName" id="contactName" placeholder="Enter Name" required>
</div>
<div class="form-group">
<label for="contactEmail">Email*</label>
<input type="email" class="form-control" name="modalEmail" id="contactEmail" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactPhone">Phone</label>
<input type="phone" class="form-control" name="modalPhone" id="contactPhone" placeholder="Enter Phone">
</div>
<div class="form-group">
<label for="contactMessage">Message*</label>
<textarea class="form-control" rows="5" name="modalMessage" placeholder="Enter detailed message" required></textarea>
</div>
<input type="submit" name="modalSubmit" class="btn btn-success" id="modalSubmit" value="Submit"/>
<button type="button" class="btn btn-default modalClose" data- dismiss="modal">Close</button>
</form>
Jquery/AJAX/JS file
var optionsB = {
url:'modalForm.php',
type:'post',
clearForm:'true',
resetForm:'true',
cache:'false',
success: function() {
alert('Thanks for your message! I will get back to you shortly.');
}
};
// bind to the form's submit event
$('#contactModalForm').submit(function() {
$(this).ajaxSubmit(optionsB);
return false;
});
PHP modalForm.php
<?php
if (isset($_POST['modalSubmit'])) {
if (!$_POST['modalName']) {
$error="<br />Please enter your name";
}
if (!$_POST['modalEmail']) {
$error.="<br />Please enter your email address";
}
if (!$_POST['modalMessage']) {
$error.="<br />Please enter a message";
}
if ($_POST['modalEmail']!="" AND !filter_var($_POST['modalEmail'],
FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s)
in your form:</strong>'.$error.'</div>';
} else {
if (mail("sitesbymiller#gmail.com", "Message from website modal form!", "
Name: ".$_POST['modalName']."
Email: ".$_POST['modalEmail']."
Phone: ".$_POST['modalPhone']."
Message: ".$_POST['modalMessage']."
On/Off Switch: ".$_POST['onoffswitch']."
Current Website: ".$_POST['modalWebsite']."
Favorite Website: ".$_POST['modalFavorite']."
Website Features: ".$_POST['modalFeatures']."
Website Purpose: ".$_POST['modalPurpose'])) {
$result='<div class="alert alert-success"><strong>Thank
you!</strong> I\'ll be in touch.</div>';
} else {
$result='<div class="alert alert-danger">Sorry, there was
an error sending your message. Please try again later.</div>';
}
}
}
?>
HTML and PHP files were good. Just had to make an adjustment to the JS/AJAX. I used the ajaxForm method instead of the ajaxSubmit and renamed my options variable as well as removed the url option, type option and cache option, and perfecto!
Big shoutout to http://jquery.malsup.com/form/#getting-started for creating such a great plugin that is user friendly and easy to use!
JS/AJAX
var options = {
clearForm:'true',
resetForm:'true',
success: function() {
alert('Thanks for your message! I will get back to you shortly.');
}
};
// pass options to ajaxForm
$('#contactModalForm').ajaxForm(options);
Related
I have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:
<div class="col-md-8 col-sm-9 wow form1 fadeInLeft">
<div class="contact-form clearfix contactForm">
<form id="form" action="php/email.php" class="contactForm"
method="post">
<div class="messages"></div>
<div class="input-field">
<input type="text" class="form-control" name="name"
placeholder="Your Name" required="">
</div>
<div class="input-field">
<input type="email" class="form-control"
name="email" placeholder="Your Email" required="">
</div>
<div class="input-field message">
<textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>
</div>
<input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">
<div class="g-recaptcha fadeInLeft" data-
sitekey=""></div>
</form>
</div> <!-- end .contact-form -->
</div> <!-- .col-md-8 -->
<script> $('#form').on('submit', function(e) {
event.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for
process.php
// $('#loader', '#form').html('<img src="img/forms/loading.gif" />
Please Wait...');
$.ajax({
type: 'POST',
url: 'php/email.php', // Your form script
data: post_data,
success: function(msg) {
var old_html = form.html()
$(form)
.html(msg).fadeIn();
setTimeout(function(){
$(form)
.html(old_html).fadeIn();
}, 4000);
},
error: function(xhr, ajaxOptions, err){
var old_html = form.html()
$(form).fadeOut(500)
.html("<h3>There was an error. Please try again.
</h3>").fadeIn();
setTimeout(function(){
$(form).fadeOut(500)
.html(old_html).fadeIn();
}, 3000);
}
});
});
</script>
And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h1>Submission successful</h1>
<h3>Thank you for contacting us!</h3>
</div>
</div>";
$to = "email#email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if (mail($to, $subject, $txt, $headers)) {
echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.
Ok, I figured it out. I added <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?
Change
$('#form').on('submit', function(e)
To
$('#form').on('submit', function(event)
Because you use
event.preventDefault();
i am making a form that on success will display a bootstrap modal with success or with fail text. The problem that i am facing is that my success part is working the modal gets displayed with the success message but the fail part brings up the modal but empty, its missing the error text. I don't seem to find the problem maybe its because i have been looking at it for a long time now. Any help would be much appreciated.
Code is the following:
HTML:
<form id="ajax-contact" method="post" action="mail.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control msg" id="name" name="name" placeholder="Your name..." required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control msg" id="email" name="email" placeholder="Your email address..." required>
</div>
<div class="form-group">
<label for="select">Category:</label>
<select class="form-control msg" id="select" name="select" required>
<option value="">Select a category</option>
<option value="Website building">Website building</option>
<option value="Template creation">Template creation</option>
<option value="Logo Design">Logo Design</option>
<option value="Mobile App">Mobile App</option>
<option value="SEO Services">SEO Services</option>
</select>
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" class="form-control msg" id="subject" name="subject" placeholder="Message subject..." required>
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Type your message here..." required></textarea>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<h1 id="form-messages" class="text-center">
</h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default center-block modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-default msg-button" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
PHP:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$subject = strip_tags(trim($_POST["subject"]));
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$select = trim($_POST["select"]);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if (empty($name) OR empty($message) OR empty($subject) OR empty($select) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "info#email.com";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Category: $select\n";
$email_content .= "Subject: $subject\n\n";
$email_content .= "Message: $message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Jquery:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
success: function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
console.log(response);
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#select').val('');
$('#subject').val('');
$('#message').val('');
},
error: function(textStatus) {
alert("asd");
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
console.log(textStatus);
// Set the message text.
if (textStatus !== '') {
$(formMessages).text(textStatus);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
}
});
});
});
Change
$(form).submit(function(event) {
to
$(form).find('[type="submit"]').click(function(event) {
And you would get
// Oops! There was a problem with your submission. Please complete the form and try again.
Problem was you are using the form tag and HTML5 wont allow to submit form untill required fields are filled, so your was form not getting submitted in first place.
I have set up a page that is still in construction and i'm building a webform for users to contact me.
When i fill the webform and hit the "send" button, message gets send succesfully and i receieve it on my mail...but when i hit the "send" button, i get re-directed off page, saying it was sent successfully.
How can i prompt user that the message was sent successfully, without getting redirected of page, and get the message in same window?
This is my HTML code
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
<div class="row">
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="text" required />
</div>
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required />
</div>
</div>
<textarea class="form-control" id="message" name="message" placeholder="Message" rows="5"></textarea>
<div class="row">
<div class="col-xs-12 col-md-12">
<button class="btn btn btn-lg">Send Message</button>
</div>
</div>
</form>
And this is my contactUs.php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$message = <<<EMAIL
$message
From: $name
My email is: $email
EMAIL;
$to = "mymail#mymail.com";
$subject = "New Customer Enquiry";
mail($to, $subject, $message, "From: " . $email);
echo "Thank you, your message has been successfully sent!";
?>
AJAX
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(){
$.post( "assets/php/contactUs.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
});
});
</script>
This is a result of successfully sent message.
Please guys help me out! Thanks!
REDIRECT OPTION
$firstpageurl = 'http://example.com';
echo "Your message has been successfully sent!";
$header('Location: '.$firstpageurl);
Use Ajax as below.Change the submit type button to a normal button by removing the type attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(event){
$.post( "config.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
event.preventDefault();
});
});
</script>
The action part of your form tag is "assets/php/contactUs.php"
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
That means that posting this form will bring you to that page. You can either code that page to send the email and redirect them back like this...
header('Location: '.$firstpageurl);
or put the php code into this first page and remove the entire action property. If you put the php on this page, you need to wrap your code in an if so that people can load the page before posting the form.
if (isset($_POST['email'])){
echo "Sent email";
[email send code here]
}
as for putting the message saying it's sent...that will only work with the second method. To do it without a full page load at all do it with ajax.
You want to use JQuery for that.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#contact").submit(function(){
var form_data=$("form").serialize();
$.post( "assets/php/contactUs.php",form_data, function( data ) {
alert(data);
});
event.preventDefault();
});
</script>
You can do it without using Javascript. Do the following:
Set the form to post to itself (e.g. if your form was on index.php, set action="index.php"
When the page loads, check $_POST to see if the form values were sent.
If the $_POST values are empty, display the form
If the $_POST values are set, do what you need to do with those values, then output your results into the page.
Here's a really simple example demonstrating what I mean.
<?php
$submitted = false;
if (isset($_POST["myinput"]) && $_POST["myinput"] != '') {
$submitted = true;
}
?>
<?php
if ($submitted == false) {
?>
<form action="index.php" method="post">
<input name="myinput"><input type="submit">
</form>
<?php } else { ?>
<h1>Form Submitted</h1>
<?php } ?>
Right now, whenever I click the submit button on the contact form on my website, it brings me to the page www.mysite.com/php/function/email.php, rather than running the email.php in the background like I want it to.
The website is supposed to allow you to submit the contact form, then the button will fade away and fade in a "Your message has been sent!", then fade back the button.
HTML:
<form name="contact form" id='contact_form' method="post" action="php/function/email.php">
<div class="row half">
<div class="6u">
<input name="name" placeholder="Name" type="text" class="text" />
</div>
<div class="6u">
<input name="email" placeholder="Email" type="email" class="text" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row half">
<div class="12u">
<input id="submit" name="submit" type="submit" value="Send Message" class="button button-icon icon icon-envelope" />
</div>
</div>
<p id="success" style="display:none">Your message has been sent! I'll get back to you soon!</p>
<p id="error" style="display:none">Please fill in all the fields and try again!</p>
JS:
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("email.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#success').fadeIn(500);
}else{
//Display the error message
$('#error').fadeIn(500);
// Enable the submit button again
$('#submit').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
};
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Example';
$to = 'example#gmail.com';
$subject = 'Example Contact Form';
$body = "
From: $name
Email: $email
---------------
Message: \n
$message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo 'sent';
} else {
echo 'failed';
}
}
?>
The .click() event of a <input type="submit"> isn't actually what causes the redirection. It instead becomes a .submit() event at the <form>.
You can either e.stopPropagation() so it doesn't reach the <form>.
//Stop form submission & check the validation
e.stopPropagation();
Or preventDefault() of the <form>'s .submit().
$('#contact_form').submit(function (e) {
e.preventDefault();
});
Note: You should also consider moving your code into a .submit() handler as most browsers support other ways of submitting a <form> than actually clicking the <input type="submit">.
The problem is that you're looking for click events on #send_message but your submit button has an id of submit. So that click event never happens.
I have asked before for help to get my php form working inside an phonegap ipa. I did exactly as I was told and everything works just fine, even inside the ipa. Only problem I have is that I get this alert right at the moment when the page loads, obviously it should show up when client forgets to fill in a required field.
Here is what I did:
FORM in contact.html
<form action="http://mobile.alicante-intermedia.com/submit_contact.php" method="get">
<div class="form-element">
<label for="txtfullname">Firstname</label>
<input id="txtfullname" name="FirstName" type="text" placeholder="required" required />
</div>
<div class="form-element">
<label for="txtemail">Lastname</label>
<input id="txtemail" name="LastName" type="text" placeholder="required" required />
</div>
<div class="form-element">
<label for="txtcontact">Email</label>
<input id="txtcontact" name="Email" type="email" placeholder="optional" />
</div>
<div class="form-element">
<label for="txtmessage">Message</label>
<textarea id="txtmessage" name="MessageText" placeholder="required" rows="5" required ></textarea>
</div>
<input type="button" onclick="submit()" value="submit contact"/>
</form>
Then I created a jquery_form.js file which loads only inside the conatct.html
$.post('http://mobile.alicante-intermedia.com/submit_contact.php', {
// These are the names of the form values
FirstName: $('#FirstName_input').val(),
LastName: $('#LastName_input').val(),
Email: $('#Email_input').val(),
MessageText: $('#MessageText_input').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
And the php looks like this:
<?php
// VARS
$FirstName=$_GET["FirstName"];
$LastName=$_GET["LastName"];
$Email=$_GET["Email"];
$MessageText=$_GET["MessageText"];
$Headers = "From:" . $Email;
//VALIDATION
if(
$FirstName=="" ||
$LastName=="" ||
$Email=="" ||
$MessageText==""
) {
echo "Error";
} else {
mail("myemail#email.com","mobile app message",$MessageText, $Headers);
echo "Success";
}
?>
Everything works fine except the alert screen. Anyone here who has an idea what went wrong?
Your JavaScript code is "bare", not wrapped in any function or attached to any event handler, and therefore executes as soon as it is loaded - so it immediately posts an empty form when the jQuery script is first parsed.
Place it into the onclick event handler for the submit button:
// When the document has loaded...
$(document).ready(function() {
// Bind this action as a function to be executed when the button is clicked...
$('input[type="button"][value="submit contact"]').click(function() {
$.post('http://mobile.alicante-intermedia.com/submit_contact.php', {
// These are the names of the form values
// EDIT: You have the wrong ids on these...
FirstName: $('#txtfullname').val(),
LastName: $('#txtemail').val(),
Email: $('#txtcontact').val(),
MessageText: $('#txtmessage').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
});
});
Since it is bound in the JavaScript code, remove the onclick from the button in your markup:
<input type="button" value="submit contact"/>
Edit:
The PHP you have is looking for values in $_GET, but you have posted them from jQuery. Look instead in $_POST.
$FirstName=$_POST["FirstName"];
$LastName=$_POST["LastName"];
$Email=$_POST["Email"];
$MessageText=$_POST["MessageText"];