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();
Related
I've try so may different ways to make this work, but no luck. Every time I submit the form the success swal alert is the one firing even on empty fields.
This is my HTML
<!-- Content -->
<div class="content">
<form role="form" id="form" action="assets/php/mail.php" method="post">
<div class="row 50%">
<div class="6u 12u(mobile)">
<label for="name"></label>
<input id="name" type="text" name="name" placeholder="Name"/>
<span></span>
</div>
<div class="6u 12u(mobile)">
<label for="email"></label>
<input id="email" type="email" name="email" placeholder="Email"/>
</div>
</div>
<div class="row 50%">
<div class="12u">
<textarea id="message" name="message" placeholder="Message" rows="7"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="buttons">
<li><input id="submit-button" type="submit" class="special" value="Send" /></li>
</ul>
</div>
</div>
</form>
</div>
This is JS The empty swal I.m using it to clear the form once is submitted is the only way that I got it to work.
$(document).ready(function(){
$('#form').on('submit',function(e) { //Don't foget to change the id form
$.ajax({
url:'assets/php/mail.php', //===PHP file name====
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
//Success Message == 'Title', 'Message body', Last one leave as it is
swal({
type: 'success',
title: 'Submmited',
text: 'Your message has been send!'
}).then((result) => {
if (result.value) {
$("#name").val("");
$("#email").val("");
$("#message").val("");
swal()
}
});
},
error:function(data){
//Error Message == 'Title', 'Message body', Last one leave as it is
swal({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: '<a href>Why do I have this issue?</a>'
})
}
});
e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
});
});
This is my PHP I use so many different php codes for this but this is the one that actual work best for me.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../../contact.html");
exit;
}
$recipient = "php_test#knobcode.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
mail($recipient, $subject, $email_content, $email_headers);
header("Location: ../../contact.html");
Try checking the inputs in the submit handler:
$('#form').on('submit',function(e) {
e.preventDefault();
if( $(this).find("[name='name']").val()!="" && // If the 3 aren't empty, it proceeds.
$(this).find("[name='email']").val()!="" &&
$(this).find("[name='message']").text()!=""
){
// The rest of your code here...
}else{
alert("Please fill the form before submitting!"); // Or use a swal...
}
});
About Ajax: The success callback fires when the Ajax resquest is successful regardless of the data sent. The error callback fires when the Ajax request cannot be completed... Like because of a wrong URL or something.
I have read many forums where this exact question posted but there is no satisfactory answer. Some posts seem to have found out how to make it work but the answer is not shared or only partly answered.
the answer that i see the most is (but don't know how to use it):
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post("sendemail.php", $(".contact-form").serialize(),function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
return false;
});
the problem with this is that $_POST is not being sent. The mail function is working but the mail contents are blank
my mail message:
Name:
Email:
Subject:
Message:
exactly this is in my mail when I fill the form with data and nothing is being sent
main.html
<h4>Contact Form</h4>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-5">
<div class="form-group">
<input type="text" class="form-control" name="subject" required="required" placeholder="Subject">
</div>
<div class="form-group">
<input type="text" class="form-control" name="name" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" required placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
</div>
</div>
<div class="col-sm-7">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
</div>
</form>
sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'myEmail#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
Is your form possibly getting submitted twice? (once completed and then blank) The html form is already fully wired to POST without the use of the submit handler, which is redundant.
If I'm going to submit a form via AJAX, I typically set only the id of the form (i.e. no action and no method attributes) and I use a regular button (not submit) as the submit button. This makes it clear that jQuery will be handling the POSTing.
<form id="main-contact-form" class="contact-form" role="form">
...fields
<button id="btn_submit" class="btn btn-primary">Submit</button>
</form>
Then in jQuery
'use strict';
var form = $('.contact-form'),
btn_submit = $('#btn_submit');
btn_submit.on('click', function(e) {
e.preventDefault(); //prevent default button behavior
$.post('sendemail.php', form.serialize(),function(result){
if(result.type == 'success'){
form.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
Change your "jquery" code as shown below:
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
$this = $(this);
$.post(
"sendemail.php",
$(".contact-form").serialize(),
function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
},
'json' // expecting a JSON response from server
);
});
I think you have multiple forms with the css class .contact-form in the same page. If you want to submit this form, then you can use form id selector.
<script type="text/javascript">
$(function() {
$('#main-contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>
Or you can write the code using the css selector as follows:
<script type="text/javascript">
$(function() {
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>
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 } ?>
How would I go about showing the response from a submitted contact form (on the same page underneath the form) rather than sending the user to a new page after the submission?
I have seen some people creating a div element, and then putting the received response into it. Is that a recommended approach?
Here is what I have so far:
PHP:
<?php
$name =$_GET['name'];
$email =$_GET['name'];
$message =$_GET['name'];
$to = "support#loaidesign.co.uk";
$subject = "";
$message = "";
$headers = "From: $email";
if(mail($to,$subject,$message,$headers))
{
echo "<h2>Thank you for your comment</h2>";
}
else{
echo "<h2>Sorry, there has been an error</2>";
}
?>
and here is the HTML:
<div class="wrapperB">
<div class="content">
<form id="contactForm" action="assets/email.php" method="get">
<label for="name">Your Name</label>
<input name="name" id="name" type="text" required placeholder="Please enter your name">
<label for="email">Email Address</label>
<input name="email" id="email" type="email" required placeholder="Please enter your email address here">
<label for="message">Message</label>
<textarea name="message" id="message" required></textarea>
<button id="submit" type="submit">Send</button>
</form>
</div>
</div>
</div>
This is a working example using the suggested example from the JQuery site and pajaja's answer.
Solution:
Place this in the <head> of your webpage.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
OR
Download JQuery and include it the same way.
Form:
Your contact form remains un-changed.
<form id="contactForm" action="assets/email.php" Method="POST">
<label for="name">Your Name</label>
<input name="name" type="text" required placeholder="Please enter your name">
<label for="email">Email Address</label>
<input name="email" type="email" required placeholder="Please enter your email address here">
<label for="message">Message</label>
<textarea name="message" required></textarea>
<button type="submit">Send</button>
</form>
Returned Data:
Add your response element where you want in the body.
<div id="contactResponse"></div>
Javascript:
Now place (preferably just before </body>) the javascript code:
<script>
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
name: name_value,
email: email_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
Action Script:
Your contact (PHP) file remains the same but change $_GET to $_POST:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "xxx#xxx.xxx";
$subject = "";
$message = "";
$headers = "From: $email";
if( mail($to,$subject,$message,$headers) )
{
echo "<h2>Thank you for your comment</h2>";
}
else
{
echo "<h2>Sorry, there has been an error</h2>";
}
?>
Result:
This should now send the data from the form on submit and then display the returned data in the #contactResponse element. The button will also set the text to "Sent, Thank you" while also disabling the button.
You will need to use ajax for that. The simplest solution is to get jQuery javascript library an use it's .post function for which you can find documentation and examples here. In your case it will look something like this:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name_value = $("#name").val();
var email_value = $("#email").val();
var message_value = $("#message").val();
$.post("assets/email.php", { name: name_value, email: email_value, message: message_value }).done(function(data) {
$("#response").html(data);
});
});
})
</script>
Also your PHP code is wrong:
$name =$_GET['name'];
$email =$_GET['name'];
$message =$_GET['name']
You are getting $_GET['name'] for all 3 variables.
edit:
I added a complete example but it is not tested it's just so you can have an idea how to do what you want. Also since this is using HTTP POST request, you will need to edit your PHP so it gets values $_POST array, not $_GET. Also you will need to add a <div id="response"></div> where you want to display the response.
You can just keep it on the same page. For example, if your form is on contact.php, just echo your code like so:
<form action='' method='post'>
<input type='test' name='name' placeholder='Your name here' required='required' /><br />
<input type='submit' value='submit' name='contact' />
</form>
<?php
if(isset($_POST['contact']) && !empty($_POST['name'])){
echo "You submitted this form with value ".$_POST['name'].".";
}
?>
Of course this will reload that page. If you don't want the page to be reloaded, you need to use ajax.
I did this with the Jquery Form Plugin. There's another here.
My use case was a lot more involved. It included uploading a file along with some user entered fields and basic auth credentials in the header as well. The Form plugin handled them all using the normal $.ajax fields.
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.