Ajax contact form attachment - php

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.

Related

Unable to implement reCaptcha in HTML 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.

Contact Form Not Found Error after submitting

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

unsuccessful clearing of form values/content after successful submission

Each time, I submit my form, the expected reset function is not clearing my form. Please how should I clear my form my codes(HTML, PHP, JS) follows below.
HTML codes:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" class="form-control">
</div>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Subject *</label>
<input type="text" name="subject" class="form-control" required="required">
</div>
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
Javascript code is below:
jQuery(function($) {'use strict',
......
......
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
$("#main-contact-form")[0].reset();
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
......
......
});
And last of all is my PHP code:
<?php
$status = array(
'type'=>'success',
'message'=>'Thank you for contacting us. As soon as possible we will contact you!'
);
$fail = array(
'type'=>'fail',
'message'=>'Please try again. Your mail could not be delivered!'
);
$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 = 'email#mail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
header('Content-type: application/json');
if($success){
echo json_encode($status);
}
else{
echo json_encode($fail);
}
?>
Try this code
$("#main-contact-form")[0].reset();
One important thing i was actually missing was that I actually used the reset function before I outputted the obtained message from the server.Looking at my code above, one will discover that i have in my javascipt code the line below:
.done(function(data){
$("#main-contact-form")[0].reset();
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
which I corrected to become this one below:
.done(function(data){
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
$('#main-contact-form')[0].reset();
//$('#main-contact-form').trigger("reset");
});
A BIG THANKS TO YOU GUYS!

Show message after submit form without refreshing the page

I'm trying to make my contact form and i want it to show message (pop up, as a or anything else) when it's successfully sent or error when it can't be sent. But i don't know how to do it. I tried a lot of things and nothink worked for me.
Here is my html code:
<form id="contact-form" action="wyslij.php" method="POST">
<div class="form-group col-lg-6 col-md-6 col-xs-12">
<input type="text" name="name" value="" placeholder="Imie">
</div>
<div class="form-group col-lg-6 col-md-6 col-xs-12">
<input type="text" name="subject" value="" placeholder="Temat">
</div>
<div class="form-group col-lg-6 col-md-6 col-xs-12">
<input type="email" name="email" value="" placeholder="Email">
</div>
<div class="form-group col-lg-6 col-md-6 col-xs-12">
<input type="text" name="phone" value="" placeholder="Telefon">
</div>
<div class="form-group col-xs-12">
<textarea name="message" placeholder="Wiadomość"></textarea>
</div>
<div class="form-group col-xs-12 clearfix">
<input type="submit" class="pull-right" name="submit" value="Wyślij">
</div>
</form>
and here is my php code:
<?php
$owner_email = "kernelus1992#gmail.com"; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< tutaj wpisz adres email na który mają byc wysyłane maile
$headers = "From: ".$_POST["email"]."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: 8bit";
$subject = 'Wiadomość ze strony internetowej';
$subject = "=?utf-8?B?".base64_encode($subject)."?=";
$messageBody = "";
if($_POST['name']!='nope'){
$messageBody .= 'Imię i nazwisko: ' . $_POST["name"] ."\n";
$messageBody .= "\n";
}
if($_POST['email']!='nope'){
$mailnadawcy = $_POST['email'];
$messageBody .= 'Email: ' . $_POST['email'] . "\n";
$messageBody .= "\n";
}else{
$headers = '';
}
if($_POST['subject']!='nope'){
$messageBody .= 'Temat: ' . $_POST['subject'] . "\n";
$messageBody .= "\n";
}
if($_POST['phone']!='nope'){
$messageBody .= 'Telefon: ' . $_POST['phone'] . "\n";
$messageBody .= "\n";
}
if($_POST['message']!='nope'){
$messageBody .= 'Treść: ' . $_POST['message'] . "\n";
}
if($_POST["stripHTML"] == 'true'){
$messageBody = strip_tags($messageBody);
}
mail($owner_email, $subject, $messageBody, $headers);
?>
You can do it through AJAX.
<script>
$(document).ready(function(){
$("#contact-form").on("submit", function(e){
e.preventDefault();
dataString = jQuery('form#contact-form').serialize();
jQuery.ajax({
type: "POST",
url: "full_path/wyslij.php",
data: dataString,
success: function(data)
{
alert('Form successfully submitted.')
},
error: function(data)
{
alert('Form not submitted.')
}
});
});
});
</script>
Also form action should be removed:
<form id="contact-form" method="POST">
You will have to use javascript or jQuery if you don't want the page to reload, in jQuery for instance you can do:
$("#contact-form").on("submit", function(e){
e.preventDefault();
alert("Form submitted");
})
This doesn't handle validation, handling of input etc, I'd suggest making an Ajax request to one of your php files to handle the form data.
jQuery.post()
If this is a route you want to take, I'll write a small example

Contact form won't submit data

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.

Categories