after sending message on contact form, results shows 404 error instead of success message. I have tried many times, i don't know what is missing. Any help will be very appreciated.
Second issue is also there, it shows:
Uncaught TypeError: $ is not a function
at contact.js?ver=20170915:1
here is the html code
<!-- Start Contact Form -->
<div class="col-lg-4 col-md-5 col-xs-12">
<div class="alert alert-info text-center " role="alert">
<h5>Contact</h5>
</div>
<form id="contact-form" method="post" action="contact.php" role="form">
<form role="form" id="contactForm" class="contact-form" data-toggle="validator">
<div class="form-group">
<div class="controls">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" required data-error="Please enter your name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" name="email" class="email form-control" id="email" placeholder="Email" required data-error="Please enter your email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" name="msg_subject" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="3" name="message"placeholder="Massage" class="form-control" required data-error="Write your message"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-block bg-info">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
<!-- Contact Form Section End -->
And i have added contact.php page
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Subject is required ";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
//Add your email here
$EmailTo = "chandanicfai1#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
contact.js file is
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "contact.php",
data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
and also form validator
https://github.com/1000hz/bootstrap-validator/blob/master/js/validator.js
Related
<!-- THIS IS USING GOOGLES reCaptcha V2 -->
<?php
if(isset($_POST['ContactButton'])) {
$url = "https://www.google.com/recaptcha/api/siteverify";
$privateKey = "##########################";
$response = file_get_contents($url."?secret=".$privateKey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
$error = "";
$successMsg = "";
if ($_POST) {
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$error .= "The email is invalid!<br>";
}
if (!$_POST['email']) {
$error .= "An email address is required!<br>";
}
if (!$_POST['subject']) {
$error .= "A subject is required!<br>";
}
if (!$_POST['body']) {
$error .= "Content in the body is required!<br>";
}
if ($error != "") {
$error = '<div class="alert alert-danger" role="alert"><strong>There is an error with your form!</strong><br>' . $error . '</div>';
} else {
$emailTo = 'contactform#########.com';
$subject = $_POST['subject'];
$body = $_POST['body'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $subject, $body, $headers)) {
$successMsg = '<div class="alert alert-success" role="alert">The message has successfully been sent. We will contact you ASAP!</div>';
} else {
$error = '<div class="alert alert-danger" role="alert">There was a problem sending your message, please try again later!</div>';
}
}
}
} else {
$captchaFail = '<div class="alert alert-danger" role="alert"><strong>There is an error with your form!</strong><br>reCaptcha Verification Failed, Please Try Again.</div>';
}
}
?>
<div class="jumbotron" id="contact-us-co" style="display: none">
<p>Contact Us:
<br><br>
<form method="POST" class="container">
<h2 style="text-align:center;">***Contact Us***</h2>
<br>
<div id="error"><?php echo $successMsg ?><?php echo $error ?><?php echo $captchaFail ?></div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputSubject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">
</div>
<label for="inputBody">Message</label>
<div class="form-group input-group">
<textarea class="form-control" aria-label="With textarea" placeholder="Body" name="body" id="body"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="###################"></div>
<br>
<button type="submit" class="btn btn-primary" name="ContactButton" id="ContactButton">Submit</button>
</form> </p>
</div>
Solution #1 (not sure how to add this code)
code to prevent refresh:
document.getElementById('ContactButton').addEventListener('click', function(event) {
event.preventDefault();
}, false);
Solution #2
After form refresh reset back to the Contact Page: (I used onClick for behaviors)
Contact Us
It's a default html form behavior. If you want to send form data without page reloading you need to looking for AJAX (or AjaxForm plugin):
F.e:
jQuery AJAX submit form
I am new to Web development and I am trying to implement reCaption in my HTML form.
I tried many online tutorials but I was unable to implement it propoerly in my code.
Head :
<script src="https://www.google.com/recaptcha/api.js?render=6LfRQZ4UAAAAAAuMMBQhrBVmyjkVsD"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfRQZ4UAAAAAAuMMBhzvMWVmyjkVsD', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
</script>
Form :
<form id="ajax-contact" method="post" action="mailer.php">
<fieldset>
<div class="form-field">
<input type="text" id="name" name="name" placeholder="Full Name" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input type="email" id="email" name="email" placeholder="Email" value="" required="" aria-required="true" class="full-width"placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="telno" type="text" id="telno" placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="subj" type="text" id="subj" placeholder="Subject" value="" class="full-width">
</div>
<div class="form-field">
<textarea id="message" name="message" placeholder="Leave Message" value="" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
<div class="form-field">
<button id="submit" type="submit" name="submit" class="full-width btn--primary">SEND</button>
<div class="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
mailer.php :
<?php // Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '6LfRQZ4UAAAAAJhdTvqgZyMJB-HO4XL_';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
// Verified - send email
} else {
// Not verified - show form error
}
} ?>
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$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"]);
$telno = trim($_POST["telno"]);
$subj = trim($_POST["subj"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "user#mail.com";
$subject = "New contact from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Telephone Number: $telno\n";
$email_content .= "Subject : $subj\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
app.js :
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-field');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #telno, #subj, #message').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
I want add reCatcha in this form to avoid spammers.
I tried official google docs also but I was unable to implement that properly in my code.
Thanks in advance for any solution.
I am having problem with ajax submit form with angular, when i click submit my entire page is reloaded?
Where can be the problem, here is my code
/*
Create the controller and inject Angular's $scope
*/
// resource2Controller
(function () {
'use strict';
angular.module("aluPlanetApp").controller('resource2Controller', resource2Controller);
resource2Controller.$inject = ['$scope'];
resource2Controller.$inject = ['$http'];
function resource2Controller($scope, $http) {
activate();
function activate() {
$scope.title = 'Contact';
$scope.id = '2';
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function (contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method: 'POST',
url: 'contact-form.php',
data: $.param($scope.formData), //param method from jQuery
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function (data) {
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result = 'bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
}
}
})();
And contact-form.php
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('something#test.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
HTML
<div ng-controller="resource2Controller" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" >
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
Mhh I belive that maybe your problem is in the HTML which I can't see right now so make sure that you are not using the submit button. I mean Instead of <input type="submit"... use <input type="button"...Here is a reference How do I make an HTML button not reload the page
On your HTML, you call your controller ContactController while at the Angular side you call it resource2Controller. Those two should match or Angular doesn't know what to do.
I've made a contact form which works, but now I need it to be able to send an attachment too. I have found some examples but I cannot get them to work with my existing code. I'd prefer to keep as much of the form intact as the css is the way I'd like it.
I've omitted the the captcha and css in the code below.
<div class="contact-box" id="contact-form">
<div class="contact-form">
<form name="contact-form" action="">
<div class="name">
<span class="fa fa-user"></span>
<input id="name" placeholder="Name">
<label class="error" for="name" id="name_error"><i class="fa fa-exclamation-triangle"></i>Please enter your name.</label>
</div>
<div class="email">
<span class="fa fa-envelope"></span>
<input id="email" placeholder="Email">
<label class="error" for="email" id="email_error"><i class="fa fa-exclamation-triangle"></i>Please enter your email address.</label>
</div>
<div class="message">
<span class="fa fa-pencil"></span>
<textarea id="message" placeholder="Your Message"></textarea>
<label class="error" for="message" id="message_error"><i class="fa fa-exclamation-triangle"></i>Please enter your message</label>
</div>
<label class="attachment">
<input type="file" id="fileattachment"/>
<span>Upload Booking Request Form</span>
</label>
<div class="submit">
<input type="submit" name="submit" class="buttonsubmit" id="contact" value="Send">
</div>
</form>
</div>
</div>
<div class="contact-box">
<div class="contact-confirmation">
<i class="fa fa-paper-plane"></i>
<h3>Thanks for your message.</h3>
<h4>We'll be in touch soon!</h4></div>
</div>
<script>
$(function() {
//Hide send confirmation
$(".contact-confirmation").hide();
//Validate form
$('.error').hide();
$("input#contact").click(function() {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("textarea#message").val();
if (message == "") {
$("label#message_error").show();
$("textarea#message").focus();
return false;
}
//Attachment part???
var attachment = $("#fileattachment")[0].files
//Send form
var dataString = 'name=' + name + '&email=' + email + '&message=' + message + '&attachment=' + attachment;
jQuery.ajax({
type: "POST",
url: "processemail.php",
data: dataString,
success: function() {
jQuery(".contact-confirmation").fadeIn(1000);
jQuery(".contact-form").hide();
}
});
return false;
});
});
</script>
//processemail.php
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$sendto = $_POST["sendto"];
$sendto = 'overhere#example.com';
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body><strong>From: </strong>' . $name . '<br /><strong>Email: </strong>' . $email . '<br /><br /><strong>Message: </strong><br />' . $message . '</body></html>';
mail($sendto, $subject, $message, $headers);
?>
HTML with your form but some modifications. I use button submit and in the php, check POST and FILES variables. You need copy FILE to path. Find in google how copy file $_FILES to path.
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<div class="contact-box" id="contact-form">
<div class="contact-form">
<form id="data" method="post" enctype="multipart/form-data">
<!--<form name="contact-form" action=""> -->
<div class="name">
<span class="fa fa-user"></span>
<input id="name" placeholder="Name" name="name">
<label class="error" for="name" id="name_error"><i class="fa fa-exclamation-triangle"></i>Please enter your name.</label>
</div>
<div class="email">
<span class="fa fa-envelope"></span>
<input id="email" placeholder="Email" name="email">
<label class="error" for="email" id="email_error"><i class="fa fa-exclamation-triangle"></i>Please enter your email address.</label>
</div>
<div class="message">
<span class="fa fa-pencil"></span>
<textarea id="message" placeholder="Your Message" name="message"></textarea>
<label class="error" for="message" id="message_error"><i class="fa fa-exclamation-triangle"></i>Please enter your message</label>
</div>
<label class="attachment">
<input type="file" id="fileattachment" name="file"/>
<span>Upload Booking Request Form</span>
</label>
<div class="submit">
<input type="submit" name="submit" class="buttonsubmit" id="contact" value="Send">
</div>
<button type="submit">Go</button>
</form>
</div>
</div>
<div class="contact-box">
<div class="contact-confirmation">
<i class="fa fa-paper-plane"></i>
<h3>Thanks for your message.</h3>
<h4>We'll be in touch soon!</h4></div>
</div>
<script>
$(function() {
//Hide send confirmation
$(".contact-confirmation").hide();
//Validate form
$('.error').hide();
/*
$("input#contact").click(function() {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("textarea#message").val();
if (message == "") {
$("label#message_error").show();
$("textarea#message").focus();
return false;
}
//Attachment part???
var attachment = $("#fileattachment")[0].files
//Send form
var dataString = 'name=' + name + '&email=' + email + '&message=' + message + '&attachment=' + attachment;
});
*/
$("form#data").submit(function(){
console.log($(this));
var formData = new FormData($(this)[0]);
$.ajax({
url : 'processemail.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
</body>
</html>
And in the php
<?php
//var_dump($_POST);
//var_dump($_FILES);
$uploads_dir = ""; /* local path */
if(isset($_FILES['file']) && ($_FILES['file']['error'] == 0) ) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "{$uploads_dir}{$name}");
}
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//$sendto = $_POST["sendto"];
$sendto = 'overhere#example.com';
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body><strong>From: </strong>' . $name . '<br /><strong>Email: </strong>' . $email . '<br /><br /><strong>Message: </strong><br />' . $message . '</body></html>';
mail($sendto, $subject, $message, $headers);
?>
You need to submit the form using the formData object.
$("form").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
This should do the job.
I have a JSON code in a sendemail.php file for my Bootstrap 3 contact form. The form is able to send an email to the specified email address but there is no data being submitted. I get blank emails with labels and the header 'unknown sender'. Please help solve this.
This is the bootsrap form code chunk
<div class="col-sm-6">
<h1>Contact Form</h1>
<p>Please contact us using the form or our contact details are available here if you'd like to contact us via Email or Phone.</p>
<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-6">
<div class="form-group">
<input type="text" name="Name" class="form-control" required placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="Email" class="form-control" required placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="Message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</div>
</div>
</form>
</div><!--/.col-sm-6-->
This is the main.js code where the AJAX for contact form is present
jQuery(function($) {
$(function(){
$('#main-slider.carousel').carousel({
interval: 5000,
pause: false
});
});
//Ajax contact
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
//smooth scroll
$('.navbar-nav > li').click(function(event) {
if(!$( this ).attr( 'href' ).match(/^#/)) return;
event.preventDefault();
var target = $(this).find('>a').prop('hash');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 500);
});
//scrollspy
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
//PrettyPhoto
$("a.preview").prettyPhoto({
social_tools: false
});
//Isotope
$(window).load(function(){
$portfolio = $('.portfolio-items');
$portfolio.isotope({
itemSelector : 'li',
layoutMode : 'fitRows'
});
$portfolio_selectors = $('.portfolio-filter >li>a');
$portfolio_selectors.on('click', function(){
$portfolio_selectors.removeClass('active');
$(this).addClass('active');
var selector = $(this).attr('data-filter');
$portfolio.isotope({ filter: selector });
return false;
});
});
});
This is the sendemail.php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = $_POST['Name'];
$email = $_POST['Email'];
$subject = $_POST['Subject'];
$message = $_POST['Message'];
$email_from = $email;
$email_to = 'myemail#domain.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;
?>
You are missing the name attribute in your html input tags
This is required for the server side variables, for example:
$name = $_POST['Name'];
will get value from
<input type="text" name="Name" class="form-control" required placeholder="Name">
<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-6">
<div class="form-group">
<input name="Name" type="text" class="form-control" required placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input name="Email" type="text" class="form-control" required placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="Message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-danger btn-lg" value="Send Message">
</div>
</div>
</div>
</form>
<?php
if(isset($_POST['submit'],$_POST['Name'],$_POST['Email'],$_POST['Subject'],$_POST['Message'])){
$name = $_POST['Name'];
$email = $_POST['Email'];
$subject = $_POST['Subject'];
$message = $_POST['Message'];
$email_from = $email;
$email_to = 'myemail#domain.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.'>');
$response = array();
if($success){
$response['success'] = true;
$response['message'] = 'Email sent!';
}else{
$response['success'] = false;
$response['message'] = 'Email sent!';
}
}else{
$response['success'] = false;
$response['message'] = 'post variables are not set';
}
echo json_encode($response);
//die;
Change this line in main.js:
$.post($(this).attr('action'), function(data) {
to:
$.post($(this).attr('action'), $(this).serialize(), function(data) {
It will now submit the data.