I'm building a website for a friend. He has a basic "Contact Me" section. I'm wanting to use AJAX and PHP to submit the form.
Here is the form html.
div class="contactme" id="contactme">
<form class="form-horizontal" method="post" name="myemailform" id="myform" action="form-to-email.php">
<fieldset>
<h2>Let's Create Together</h2>
<hr class="small">
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">E-Mail</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="email" name="visitor_email" placeholder="E-Mail">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea class="form-control" rows="8" name="message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" name="submit" id="submitbutton" class="btn btn-primary mainButton">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
Here is jquery AJAX code snippet.
//AJAX FORM SUBMISSION
$(document).ready(function(){
$('#submitbutton').on('submit', function(){
//Stop the form from submitting itself to the server.
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.ajax({
type: "POST",
url: 'form-to-email.php',
data: {name: email},
success: function(){
alert(data);
}
});
});
});
And here is my PHP file that e-mails the responses from the user.
<?php
if (!isset ($_POST ['submit']))
{
//This page should not be accessed directly. Need to submist the form.
echo "error, you need to submit the form!";
}
$name = $_POST ['name'];
$visitor_email = $_POST ['visitor_email'];
$message = $_POST ['message'];
//Validation
if(empty ($name)||empty ($visitor_email))
{
echo "Name and email are mandatory!";
exit();
}
else {
echo "Submit Successful!";
header("Location: index.html");
exit();
}
$email_from = 'info#joshkelley.video'; //<== Put your email address here
$email_subject = "New Form Submission";
$email_body = "You have received a new message from the user $name.\n".
"E-mail Address: $visitor_email\n".
"Here is the message: $message\n".
$to = "brandontetrick#gmail.com"; // <==Put your email address here
$headers = "From: $email_from \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done
?>
Overall goal is for a basic submission of a "Contact Me" message, but the user doesn't leave the page. Every time I press the submit button, my validation fails and I get "Name and email are mandatory!" message.
The site is live if you want to take look. Still a work in progress.
joshkelley.video
you miss data, as you post only name
$(document).ready(function(){
$('#submitbutton').on('submit', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.ajax({
type: "POST",
url: 'form-to-email.php',
data: {name: name, email: email}, /* there was your mistake */
success: function(reponse){
alert(response);
window.location.href = 'index.html'; /* wherever you need */
}
});
});
});
EDIT: as I think (from your other post) you want user to be redirected, don't try doing this with form-to-email.php but according to response.
EDIT II: remove action from form just to make sure
Related
HTML:
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Name" required="required">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email Address" required="required">
</div>
</div>
</div>
<div class="form-group">
<input type="tel" name="subject" class="form-control" placeholder="Phone" required="required">
</div>
<div class="form-group">
<textarea name="message" id="message" class="form-control" rows="4" placeholder="Enter your message" required="required"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn-submit">Send Now</button>
</div>
</form>
PHP:
<?php
$mail='kenhaki#gmail.com';
$nombre = $_REQUEST['name'];
$telefono = $_REQUEST['subject'];
$email = $_REQUEST['email'];
$mensaje = $_REQUEST['message'];
$headers = 'From: ccontacto#nhtt.com.mx' . "\r\n" .
'Reply-To: cContacto#nhtt.com.mx' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$thank="gracias.html";
$message = "
nombre15: $nombre
telefono: $telefono
email: $email
mensaje: $mensaje";
if (mail($mail,"Formulario de Contacto Nuevo",$message,$headers))
Header ("Location: $thank");
?>
JS:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
I'm a beginner, I have been searching through similar questions but haven't found an explanation of why it won't get the fields from the html form.
I have tried using $_REQUEST and $_POST but none work. I have the same form in another part of the same site where it works fine, maybe here the JS is blocking it somehow?
Thanks in advance for your patience.
You're overriding the default form action with event.preventDefault(). Then all your AJAX call is doing, is requesting the contents of sendemail.php - it's not sending any data to it!
Try altering your JS code to this:
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
method: 'post',
data: $(this).serialize(),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
My contact form doesn't seem to work. I don't know what is wrong. I tried all sorts of solutions, nothing works. My pages still refreshes. Maybe anyone can spot a mistake that I did or perhaps offer alternative code? I would really appreciate your help!
return: false; doesn't work. neither does e.prevenDefault();. Don't ask why.
HTML
<form action="" method="post" id="contact-form">
<div class="row">
<div class="medium-3 columns">
<label>
<input type="text" id="name" placeholder="Your name*" name="name" required/>
</label>
</div>
<div class="medium-3 columns">
<label>
<input type="email" id="email" name="email" placeholder="Your e-mail*" required/>
</label>
</div>
<div class="medium-3 columns">
<label>
<input type="text" id="compname" name="compname" placeholder="Company name*" required/>
</label>
</div>
<div class="medium-3 columns">
<label>
<input type="text" id="website" name="website" placeholder="Website*" required/>
</label>
</div>
</div>
<div class="row">
<div class="medium-12 columns">
<label>
<textarea type="text" row="10" name="message" id="message" placeholder="Message*" required></textarea>
</label>
</div>
</div>
<div class="row">
<button type="submit" class="button large" id="sendmessage-btn"> Send Message
</button>
</div>
<div data-alert class="alert-box success radius">Your message has been sent.×
PHP
<?php
$to = 'email#email.com';
$subject = 'Message from the contact form';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$compname = trim($_POST['compname']);
$website = trim($_POST['website']);
$message = trim($_POST['message']);
$message = <<<EMAIL
Name: $name
Contact e-mail: $email
Company: $compname
Company website: $website
Message: $message
EMAIL;
if ($_POST) {
mail ($to, $subject, $message, $header);
} ?>
And JS
$(document).foundation();
var form = $('#contact-form');
var submitButton = $('#sendmessage-btn'); // Variable to cache button element
var alertBox = $('.alert-box'); // Variable to cache meter element
var closeButton = $('.close'); // Variable to cache close button element
$(form).submit(function () {
$.ajax({
type: 'get',
url: 'function.php',
data: $(form).serialize(),
success: function sendContactForm(){
$(submitButton).fadeOut(500); // Fades out submit button when it's clicked
setTimeout(function() { // Delays the next effect
$(alertBox).fadeIn(500); // Fades in success alert
}, 500);
};
});
});
$(closeButton).click(function() { // Initiates the reset function
$(alertBox).fadeOut(500); // Fades out success message
setTimeout(function() { // Delays the next effect
$('input, textarea').not('input[type=submit]').val(''); // Resets the input fields
$(submitButton).fadeIn(500); // Fades back in the submit button
}, 500);
return false; // This stops the success alert from being removed as we just want to hide it
});
// Your form is already a jquery object, don't wrap it again?
form.submit(function () {
$.ajax({
....
});
// Prevent default submit behavior of form.
return false;
});
I'm having trouble getting this contact form working on an HTML site and I can't figure out why :/
I manage to get the email to my mailbox, but it only displays the subject (which isn't that useful as it's plain text, and sometimes I get the name.
Thanks in advance if you can help.
DIV:
<div id="contactForm" class="shadow">
<div class="sepContainer"></div>
<form action="process.php" method="post" id="contact_form">
<div class="name">
<label for="name">Your Name:</label>
<p> Please enter your full name</p>
<input id="name" name="email" type="text" placeholder="e.g. Mr. John Smith" required />
</div>
<div class="email">
<label for="email">Your Email:</label>
<p> Please enter your email address</p>
<input id="email" name="emai" type="email" placeholder="example#domain.com" required />
</div>
<div class="message">
<label for="message">Your Message:</label>
<p> Please enter your question</p>
<textarea name="messagetext" id="message" cols="30" rows="4"></textarea>
</div>
<div id="loader">
<input type="submit" value="Submit" />
</div>
</form>
</div>
JS:
// Activate the contactform
$(document).ready(function() {
$(function(){
$('#contact_form').submit(function(e){
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader', form).html('<img src="images/loader.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
});
});
PHP:
<?php
$toemail = 'myemailaddress#whatever.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(mail($toemail,'CFUSU Online',$message,'From:'.$email)) {
echo 'Your email was sent succesfully.';
} else {
echo 'There was a problem sending your email.';
}
?>
Correct php code
$toemail = 'myemailaddress#whatever.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['messagetext'];
if(mail($toemail,'CFUSU Online',$message,'From:'.$email)) {
echo 'Your email was sent succesfully.';
} else {
echo 'There was a problem sending your email.';
}
I am trying to send an email with PHP and Ajax, the mailer is working but I know very little about Ajax, after reading a couple of pages of a book I have written a small piece of code and was hoping someone could point out where I am going wrong:
Here is my PHP:
<?php
$name = ($_POST['name']);
$email = ($_POST['email']);
$fsubject = ($_POST['subject']);
$message = ("Name: ". $name . "\nEmail Address: " . $email . "\n\nMessage: " . $_POST['message']);
// Set Mail
$to = "emailaddress#fakeone.com";
$headers = 'emailaddress#fakeone.com' . "\r\n";
$subject = "{$fsubject}";
$body = "{$message}";
// Send Mail
if (mail($to, $subject, $body, $header))
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
My HTML:
<div id="success" style="color:red;"></div>
<form action="" id="contactform" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Your name *</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name">
</div>
<div class="col-md-6">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Subject</label>
<input type="text" value="" data-msg-required="Please enter the subject." maxlength="100" class="form-control" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Message *</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" id="submit" value="Send Message" class="btn btn-info btn-lg" data-loading-text="Loading...">
</div>
</form>
My AJAX:
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("sendmail.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
At the moment the same page just reloads, the desired outcome is just a subtle success or failure message appearing.
Any help would be welcome!
Thanks,
Dan
Your snippet code seems to run just fine.
It must be an error either in other JS (check browser console, F12 in Chrome for example) or in your PHP.
Try this to see if ajax post fails:
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("contact.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
}).fail(function() {
alert( "error" );
});
return false;
});
});
</script>
Also, try to make sure PHP execution is fine, so remove all javascript and replace
<form action="sendmail.php" id="contactform" method="post">
Check the result of that page, it should be "Message successfully sent!".
Also, check a simple JS snippet of your code:
http://jsfiddle.net/CPtpk/
Please note that if you have another JavaScript code in your page that could be a cause for this problem. Even if your JS error is in another place it can cause JS execution to stop and so your onClick isn't executed and that's why you get your problem...
Try something like this on the JS:
<script>
$(document).ready(function() {
$('#contactform').submit(function(e) {
e.preventDefault();
$.post("sendmail.php", $(this).serialize(), function(response) {
$('#success').html(response);
});
});
});
</script>
So i downloaded a html template, and i cant get the contact form to work..
So here is the contact form:
<form id="contact" action="contact.php" method="get" />
<div class="row-fluid">
<p class="span12">
<label for="name" class="second-color">
Nome</label>
<input type="text" id="name" name="name" class="required second-color span12" maxlength="25" />
</p>
</div>
<div class="row-fluid">
<p class="span12">
<label for="email" class="second-color">
E-mail</label>
<input type="text" id="email" name="email" class="required second-color email span12" maxlength="25" />
</p>
</div>
<div class="row-fluid">
<p class="span12 multi">
<label for="comment" class="second-color">
Mensagem</label>
<textarea id="comment" name="comment" class="required second-color span12"></textarea>
</p>
</div>
ENVIAR MENSAGEM
ENVIAR MENSAGEM
<div id="loadingForm">
<img src="assets/images/loading.gif" alt="loading" />
</div>
</form>
And on the javascript file, i have this piece of code that is related to the form:
/*post operation for contact page*/
$("#contact a").click(function () {
$('#contact #loadingForm').fadeIn('slow');
/*function which validates input with required class in contact page */
var myform = $("#contact").validate({
email: true,
errorPlacement: function (error, element) {
error.appendTo();
}
}).form();
/*myform returns true if form is valid.*/
if (myform) {
var action = $("#contact").attr('action');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
web: $('#web').val(),
message: $('#message').val()
},
function (data) {
d = data;
$('.response').remove();
if (data == 'Message sent!') {
$('#contact a').attr('disabled', '');
$('#contact').append('<span class="success"></p>');
}
else {
$('#contact').append('<span class="response"></span>');
}
});
}
$('#contact #loadingForm').fadeOut('slow');
return false;
});
So now, what do i need to do for the contact work? The template is on ajax, so the form cant reload the page, because if the page is reloaded, the background music will stop.
I have to create the file contact.php, but, if i do that, the page will reloaded when i click on the button, right?
Can anyone help me with this?
Your page won't reload if you call it like you do with Ajax. Just make sure the form doesn't submit.
I would add:
$("#contact a").click(function (event) {
event.preventDefault();
To make sure your page won't reload on click.
Then in the PHP side you can use something like this:
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "emailaddress#here.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Message sent!";
?>