Contact form php and jquery - php

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!";
?>

Related

AJAX/PHP Form Data Not Submitting

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

don't send the form message if input is empty

i do have a little problem with my contact.php :(
I needed for my page a contact form (very simple, just name, email and message).
It works perfectly but it sends the message even if the inputs are empty. My inputs do have "required" but it doesn't seem to work. My php skills are not that great. But you understand for sure where the problem is.
If there are empty fields, the form should not send the message and show an alert.
My current code:
HTML
<form method="post" id="myform" action="contact.php">
<div class="field half first">
<label for="name">Ihr Name</label>
<input type="text" name="name" id="name" required="required">
</div>
<div class="field half">
<label for="email">Ihre E-Mail</label>
<input type="text" name="email" id="email" required="required">
</div>
<div class="field">
<label for="message">Ihre Nachricht</label>
<textarea name="message" id="message" rows="5" required="required"></textarea>
</div>
<ul class="actions">
<li>
Senden
</li>
</ul>
</form>
contact.php
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'mail#gmail.com';
$subject = 'Nachricht von '.$field_name;
$body_message = 'Von: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Nachricht: '.$field_message;
$headers = 'Von: '.$field_email."\r\n";
$headers .= 'Antworte an: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Ich bedanke mich für Ihre Nachricht. Bald werde ich Sie kontaktieren./ Thank you for your message.');
window.location = 'http://';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Senden fehlgeschlagen./ Could not send the message');
window.location = 'http://';
</script>
<?php
}
?>
Any ideas, how to fix that small problem? :(
I think if your goal is to prevent someone send a blank message/contact, just use "required" in the end of your input tag like this :
<input type="text" name="something" required/>
or in your case, it should be like this :
<form method="post" id="myform" action="contact.php">
<div class="field half first">
<label for="name">Ihr Name</label>
<input type="text" name="name" id="name" required>
</div>
<div class="field half">
<label for="email">Ihre E-Mail</label>
<input type="text" name="email" id="email" required>
</div>
<div class="field">
<label for="message">Ihre Nachricht</label>
<textarea name="message" id="message" rows="5" required></textarea>
</div>
<ul class="actions">
<li>
Senden
</li>
</ul>
</form>
The "required" is a simple html5 tag attribute that helps you prevent someone send a blank form. I hope it works on you, make sure you are working with html5.
There is a function in PHP called empty(). You can combine this with the $_POST function like this example:
<?php
// The form is submitted.
if(isset($_POST["submit_button"])) {
// Now check if the posted input element is empty, if empty stop by echo a error message
// Otherwhise continue executing script
if(empty($_POST["form_name"])) {
echo "You forgot to fill in this form-element.";
}else{
// Continue
}
}
?>
Read more about this function: http://php.net/manual/en/function.empty.php
Check if the form is submitted using isset() function:
isset — Determine if a variable is set and is not NULL
Then, check if the fields are filled using empty() function:
empty — Determine whether a variable is empty
// this will return true if the Submit Button is clicked
if(isset($_POST["submit_button"])) {
if(empty($_POST['name']) {
echo "Name is not filled";
} else if (empty($_POST['email']) {
echo "Email is not filled";
} else if (empty($_POST['message']) {
echo "Message is not filled";
} else {
// Your original code
}

Submit contact form without refresh (Zurb Foundation, PHP, AJAX, jQuery and JS)

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;
});

Contact form not submitting using Ajax and PHP

I'm building a contact form for my site using jQuery validation plugin, ajax call to forward the data to the PHP file, and finally sending the email. Seems like the data is not passed to the php mailer. I'm new to server side technologies, I read a lot but still can't make this working, so please advise me.
the form:
<form class="form-horizontal" role="form" id="contactForm" name="contactForm" method="post">
<div class="form-group">
<label class="col-lg-2 control-label" for="inputName">Name</label>
<div class="col-lg-10">
<input class="form-control" id="inputName" name="inputName" placeholder="Your name" type="text" value="" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputEmail">Email</label>
<div class="col-lg-10">
<input class="form-control" id="inputEmail" name="email" placeholder="your#email.com" type="email" value="" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputMessage">Message</label>
<div class="col-lg-10">
<textarea class="form-control" id="inputMessage" name="inputMessage" placeholder="Message" rows="3" required></textarea>
<button class="btn btn-success pull-right" type="submit" name="submit" id="submit">Send</button>
</div>
</div>
the javascript:
/*validate contact form */
$(function() {
$('#contactForm').validate({
rules: {
inputName: {
required: true,
minlength: 2
},
inputEmail: {
required: true,
email: true
},
inputMessage: {
required: true
}
},
messages: {
name: {
required: "name required",
minlength: "name must be at least 2 characters"
},
email: {
required: "email required"
},
message: {
required: "message required",
minlength: 10
}
},
submitHandler: function(form) {
$('form').ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"index2.php",
success: function() {
alert("message sent");
},
error: function() {
alert("due to an error msg wasnt sent");
}
});
}
});
});
php file:
<?php
if ($_POST["submit"]) {
$name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
$message = $_POST['inputMessage'];
$from = 'Demo Contact Form';
$to = 'example#example.com';
$subject = 'Message from Contact Demo ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
mail($to, $subject, $body, $from);
}
?>
$(form).serialize() doesn't include the submit field (how would it know which submit button you clicked on?), so if ($_POST['submit']) will never succeed. Use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
instead.
Or, if this script is only used for AJAX calls, and not loaded directly by the browser, you can omit that check entirely, as in Glizzweb's answer.
better use checking if:
if (isset($_POST['inputName'])){
//rest part here
}
// and see if the file is in same directory otherwise give relative path.
use this to send form content:
submitHandler: function() {
$('form').ajaxSubmit({
type:"POST",
data: $('#contactForm').serialize(),
url:"submit.php",
success: function() {
alert("message sent");
},
error: function() {
alert("due to an error msg wasnt sent");
}
});
}
In your ajax.php remove $_POST["submit"]
<?php
$name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
$message = $_POST['inputMessage'];
$from = 'Demo Contact Form';
$to = 'example#example.com';
$subject = 'Message from Contact Demo ';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
mail($to, $subject, $body, $from);
?>
In ajax page $_POST['submit'] need remove because you post values using "$(form).serialize()" and In you not post value to ajax page. remove if condition "if ($_POST["submit"]) {}" and change like this "if (!empty($_POST["inputName"])) { }"
$name = trim($_POST['inputName']);
$email = trim($_POST['inputEmail']);
.....
....
....
Try this code:
<html>
<head>
<script src="js/jquery-1.11.0.js" type="text/javascript"></script>
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/additional-methods.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#contactForm').submit(function(e){
e.preventDefault();
$('#contactForm').validate({
rules: {
inputName: {
required: true,
minlength: 2
},
inputEmail: {
required: true,
email: true
},
inputMessage: {
required: true
}
},
messages: {
name: {
required: "name value required",
minlength: "name must be at least 2 characters"
},
email: {
required: "email is required"
},
message: {
required: "message is required",
minlength: 10
}
},
submitHandler: function(form) {
alert($('form').html());
$.ajax({
type:"POST",
data: $(form).serialize(),
url:"test1.php",
success: function() {
alert("message sent");
},
error: function() {
alert("due to an error msg wasnt sent");
}
});
}
});
});
});
</script>
</head>
<body>
<form class="form-horizontal" role="form" id="contactForm" name="contactForm" method="post">
<div class="form-group">
<label class="col-lg-2 control-label" for="inputName">Name</label>
<div class="col-lg-10">
<input class="form-control" id="inputName" name="inputName" placeholder="Your name" type="text" value="" >
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputEmail">Email</label>
<div class="col-lg-10">
<input class="form-control" id="inputEmail" name="email" placeholder="your#email.com" type="email" value="" >
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="inputMessage">Message</label>
<div class="col-lg-10">
<textarea class="form-control" id="inputMessage" name="inputMessage" placeholder="Message" rows="3" ></textarea>
<input class="btn btn-success pull-right" type="submit" name="submit" id="submit" value="Send">
</div>
</div>
</body>
</html>
It is working and showing message sent and ajax call also made. you are doing some mistakes while performing ajax call. as jquery validation plugin does not provide any ajaxsubmit function instead use jquery ajax function as i have used. try it and let me know for further issue.
Change this code to fit your requirement.

Why won't my contact form email me after submission?

I am very new to PHP, so please bear with me here.
It seems like the form goes through, I don't get any errors, but I never receive an email.
Thank you in advance!!
Here is my html
<form class="form-horizontal" role="form" method="POST" id="contact-form" action="contact-form/form.php" style="padding-bottom: 5em;">
<div class="form-group">
<label class="sr-only" for="name">Name</label>
<div class="col-md-12">
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Name">
</div>
</div>
<br>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<div class="col-md-12">
<input type="email" class="form-control" name="email" id="email" placeholder="Enter Email">
</div>
</div>
<br>
<div class="form-group">
<label class="sr-only" for="message">Message</label>
<div class="col-md-12">
<textarea class="form-control" name="message" rows="10"></textarea>
</div>
</div>
<br>
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Here is my php
<?php
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST["save"]) || $_POST["save"] != "contact") {
header("Location: ../index.php"); exit;
}
// get the posted data
$name = $_POST["name"];
$email_address = $_POST["email"];
$message = $_POST["message"];
$headers = 'From: '.$email_address."\r\n" .
'X-Mailer: PHP/' . phpversion();
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Message:\n\n$message";
// send the email
mail ("myEmail", "Someone Wants a Website!", $email_content, $headers);
$to = $_POST['email'];
$subject = 'Thank you for contacting me!';
$msg = 'I have recieved your correspondence and will get back to you as soon as I can. Best regards, Mike Wilcox Designs';
mail($to, $subject, $msg);
header("Location: ../index.php"); exit;
?>
I am also using jquery validate
<script>
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
</script>

Categories