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>
Related
I am newbie for HTML and PHP programming.
When i am submitting data from form $POST is not fetching values from form and simply empty values are getting mailed .spent quite a lot time for this but couldn't figured it out..
following is part of a code of my HTML Form
<form id="main-contact-form" class="contact-form" name="contact-form" method="POST" action="sendemail.php">
<div class="form-group">
<input type="text" name="namefirst" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="emailfirst" class="form-control" placeholder="Email ID">
</div>
<div class="form-group">
<input type="tel" name="tel" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">Send</button>
</div>
</form>
following is my PHP code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for registering wth us.We will keep updating you.'
);
{
$name = $_POST["namefirst"];
$email = #trim(stripslashes($_POST["emailfirst"]));
$email_from = $email;
$email_to = '****';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" ;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
}
?>
i have tried all the possible solutions,but its just not working.Please let me know what is wrong with this.
i figured it out ..problem is not with PHP or HTML file it is with javascript code,values were not getting set there #MueyiwaMosesIkomi thanks alot becoz of this i got this problem so to solve this I did following thing:
EARLIER my code was:
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
which was not sending values. after this code its working;
var form = $('.contact-form');
var namefirst= $('.contact-form' . 'namefirst').val();
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
now its sending values but it is going on next page and showing php echo as it is,not encoding Json so i thnik
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
this part of code is not working...can anyone help regarding this??????
Thanks all of you
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 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 } ?>
I have this for document ready using jquery 1.11 from cdn and jquery migrate 1.2.1 from cdn. The ajax is to send form values to a file "mail.php" that sits in the same directory and simply checks if it was called via ajax then grabs the post variables and send them via email. It can't be a cross domain issue. Also, the alerts below confirm that it is grabbing the input values OK. This works fine for ie10+ and all other browsers.
However, for ie8+9 - the email is sent to me blank..in other words the post variables aren't being recieved?
$("#contactform").submit( function (e) {
e.returnValue=false;
e.preventDefault();
alert('form submitted');
if (checkValidation()) {
//if valid, send ajax
var name=$('#form-name').val();
var email=$('#form-email').val();
var contact_number=$('#form-contact-number').val();
var message=$('#form-message').val();
alert(name+email+contact_number+message);
$.ajax({
type: 'POST',
url: 'mail.php',
//data: JSON.stringify(parameters),
contentType: "json",
// data: $(this).serialize(),
data:{'name':name,'email':email,'contact_number':contact_number,'message':message},
dataType: "text",
cache: false,
success: function(data) {
// do something with ajax data
$('.form-response').css({color:'black',backgroundColor:'white',textAlign:'center'}).text('Thank you, we will contact you shortly.').show();
$('input').val('').trigger('blur');
$('textarea').val('').trigger('blur');
setTimeout(function(){
$('.form-response').hide();
scroll_to_top();
},3000);
},
error:function (xhr, ajaxOptions, thrownError){
console.log('error...', xhr);
//error logging
},
complete: function(){
//afer ajax call is completed
}
});
} else {
alert('Please re-enter your input and try again.');
$('input').val('');
$('textarea').val('');
$("input").trigger("blur");
$("textarea").trigger("blur");
$('#form-name').focus();
}
});
My form on index.html looks like:
<form class="form-style validate-form clearfix" id="contactform" action="mail.php" method="POST" role="form">
<div class="col-md-6"><div class="form-group"><input type="text" class="text-field form-control validate-field required" data-validation-type="string" id="form-name" placeholder="Full Name" name="name"></div>
<div class="form-group"><input type="email" class="text-field form-control validate-field required" data-validation-type="email" id="form-email" placeholder="Email Address" name="email"></div>
<div class="form-group"><input type="tel" class="text-field form-control validate-field phone" data-validation-type="phone" id="form-contact-number" placeholder="Contact Number" name="contact_number">
<input type="text" id="address-input" name="address" style="display: none!important;"></div></div><div class="col-md-6">
<div class="form-group"><textarea placeholder="Message..." id="form-message" class="form-control validate-field required" name="message"></textarea></div>
<div class="form-group"><button type="submit" id="submitBtn" class="btn btn-sm btn-outline-inverse">Submit</button></div></div>
</form>
my mail.php:
<?php
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
# is ajax
if (empty($_POST["address"])) {
$from = $_POST["name"]; // sender
$subject = 'From: ' . $from;
$email = $_POST["email"];
$tel = $_POST["contact_number"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
$textToSend = 'From: ' . $from . "\n";
$textToSend .= 'Email: ' . $email . "\n";
$textToSend .= "Phone: " . $tel . "\n";
$textToSend .= 'Message: ' . $message . "\n";
// send mail
mail("contact#domain.net", $subject, $textToSend, "From: $from\n");
echo "Thank you, we will contact you shortly.";
echo '
<script>
$("input").val("");
$("textarea").val("");
setTimeout(function(){
scroll_to_top();
},3000);
</script>
';
} else {
echo 'Thank you, we will contact you shortly.';
echo '
<script>
$("input").val("");
$("textarea").val("");
setTimeout(function(){
scroll_to_top();
},3000);
</script>
';
}
}else{
header( 'Location: http://www.myhomepage.net' ) ;
die();
}
Edit:: incase a question about it gets brought up.. I use the address field in the form to act as my "honeypot" method .. which basically means if the field address ( which is set to display none ) is filled it..then the submission was most likely a bot and will be discarded.
Probably it's that your variables are double-quoted see heere for more info https://stackoverflow.com/a/7081920/3501422
Full website: http://adamginther.com
I've used two separate tutorials to build this, one for the PHP and one for the AJAX. My goal is to build a contact form that will check for errors. If there are no errors then it will prompt users with a message saying that the message has been sent without refreshing the page.
When the website is run locally it does not display the errors until the button is pressed, when run on the server the errors are displayed on entering the page. When the contact button is pressed it loads PHP and the page goes blank.
HTML
<form action="contact.php" method="post">
<label name="firstName">Name: </label>
<input type="text" name="firstName" id="firstName">
<label class="error" for="firstName" id="name_error">I need your name.</label>
<br id="namebreak">
<br>
<label name="email" for="email" id="email_label">E-mail Address: </label>
<input type="text" name="email" id="email">
<label class="error" for="firstName" id="name_error">I need your e-mail.</label>
<br id="emailbreak">
<br>
<label name="message">Message: </label>
<textarea name="message" id="message"></textarea>
<label class="error" for="firstName" id="name_error">I need your message.</label>
<br id="messagebreak">
<br>
<input type="submit" value="Say Hello!" id="contactbutton" class="button">
JavaScript
$(function () {
$('.error').hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#firstName").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
$("#namebreak").hide();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
$("#emailbreak").hide();
return false;
}
var message = $("input#message").val();
if (message == "") {
$("label#message_error").show();
$("input#message").focus();
$("#messagebreak").hide();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone;
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function () {
$('#contactme').html("<div id='message'></div>");
$('#message').html("<p>Contact form submitted.</p>")
.append("<p>I will get back to you shortly.</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
PHP
<?php
$field_firstName = $_POST['firstName'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'gintherthegreat#gmail.com';
$subject = 'AdamGinther.com message from '.$field_firstName;
$body_message = 'From: '.$field_firstName."\n";
$body_message .= 'E-mail: ' .$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
$('#panel').show();
$('#output-inside').text('Thank you ' + firstName + ', I will get back to you as soon as I can.');
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
$('#panel').show();
$('#output-inside').text('I am sorry ' + firstName + ', but there was a problem processing your request. I can be contacted by e-mail at GintherTheGreat#Gmail.com'); </script>
<?php
}
?>
I think you need to prevent default action of the submit button.
Use,
$(function() {
$('.error').hide();
$(".button").click(function(e) {
e.preventDefault();
// Other code
});
});
change
<form action="contact.php" method="post">
to
<form action="contact.php" method="post" id="form_id">
and change
$(".button").click(function () {
to
$('#form_id').submit(function (event) {
event.preventDefault();
...
...
Just simply change the button type from submit to button so it will not submit the form and goes to php blank page by default and call the function for u.
Try the following:
<form action="contact.php" method="post" onsubmit="return false;">
Instead of using a form, why not just have an external .php (e.g. sendmail.php) script that handles your php, and then use jQuery to handle the POST.
$.post('sendmail.php',{
mail:mail,
message:message
}, function(data) {
//Echo either "success" or "false" in the sendmail.php script
if(data == "success"){
//Do something - e.g. (alert('Message has been sent');)
}else{
//Do something
}
});