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.
Related
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 need some help with this contact form im trying to fix.
The thing is that it works... kinda. i do get the messages but no success confirmation. the form just fades out a lil' bit and get's stuck i guess but the message does go through.
Any ideas of what im missing here?
<form action="#" id="contact-form">
<div class="input-group name-email">
<div class="input-field">
<input type="text" name="name" id="name" placeholder="Naam/Bedrijf" class="form-control">
</div>
<div class="input-field">
<input type="email" name="email" id="email" placeholder="Email" class="form-control">
</div>
<div class="input-field">
<input type="phone" name="phone" id="phone" placeholder="Telefoon" class="form-control">
</div>
</div>
<div class="input-group">
<textarea name="message" id="message" placeholder="Bericht" class="form-control"></textarea>
</div>
<div class="input-group">
<input type="submit" id="form-submit" class="pull-right" value="Verzenden ">
</div>
</form>
that is my form script
$('#contact-form').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true
}
},
messages: {
name: {
required: "name",
minlength: 2
},
email: {
required: "no email"
},
message: {
required: "no msg",
minlength: 2
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type: "POST",
data: $(form).serialize(),
url: "process.php",
success: function() {
$('#contact-form :input').attr('disabled', 'disabled');
$('#contact-form').fadeTo("slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor', 'default');
$('#success').fadeIn();
});
},
error: function() {
$('#contact-form').fadeTo("slow", 0.15, function() {
$('#error').fadeIn();
});
}
});
}
});
});
</script>
validation
<?php
$to = "";
$from = $_REQUEST['name'];
$subject = $_REQUEST['subject'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"subject"} = "subject";
$fields{"message"} = "message";
$body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$send = mail($to, $subject, $body, $headers);?>
and finally my process.php script. any help would be appreciated. thanks.
<div id="success">
<span>
<p>Your message was sent successfully! I will be in touch as soon as I can.</p>
</span>
</div>
<div id="error">
<span>
<p>Something went wrong, try refreshing and submitting the form again.</p>
</span>
</div>
I have this piece of code as well at the end in the HTML but it just prints with or without submitting
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>
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!";
?>