Getting a 500 Internal Server error on the client side when trying to test with phpmailer.
Based on my knowledge, it's throwing the error due to a misplaced or nonexistent file, but the file is actually there.
Here's a screenshot of the file structure for the site and for the includes file
PHP
<?php
// $email and $message are the data that is being
// posted to this page from our html contact form
// $email = $_POST['email'] ;
// $message = $_POST['message'] ;
// When we unzipped PHPMailer, it unzipped to
// based on where this php file sites, i gave it the following path.
// But also tried, '../includes/phpmailer.class.phpmailer.php'
// and also tried, 'phpmailer.class.phpmailer.php'
require_once("includes/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587;
$mail->Username = "patrick.johnson9#gmail.com";
$mail->Password = "corner09";
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddAddress("im#pbj.me","First Last")
$mail->Subject = "PHPMailer Test Subject via smtp (Gmail), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
JAVASCRIPT
// Form submission
$("#form-apply").submit(function(e){
e.preventDefault();
// get the form data
var formData = {
"name": $("input[name='name']").val(),
"email": $("input[name='email']").val(),
"message": $("input[name='message']").val(),
// "upload": $("textarea[name='upload']").val()
};
console.log(formData);
$.ajax({
type: "POST", //define the type of HTTP verb we want to use
url: "../includes/form-apply.php",
data: formData, //our data object
dataType: "json",
encode: true
}).done(function(data){ //using the done promise callback
// log the data to the console so we can see it
console.log(data);
if(! data.success){
if (data.errors.name){
$("#name").parent().addClass("has-error");
$(".name-group").append("<div class='help-block'>" + data.errors.name + "</div>");
// $("#name").attr("placeholder", data.errors.name);
}
if(data.errors.email){
$("#email").parent().addClass("has-error");
$(".email-group").append("<div class='help-block'>" + data.errors.email + "</div>");
}
if(data.errors.subject){
$("#subject").parent().addClass("has-error");
$(".subject-group").append("<div class='help-block'>" + data.errors.subject + "</div>");
}
if(data.errors.message){
$("#message").parent().addClass("has-error");
$(".message-group").append("<div class='help-block'>" + data.errors.message + "</div>");
}
} else {
$(".form-apply").prepend("<div class='alert alert-success'>" + data.message + "</div>")
$("input, textarea").val("");
}
}).fail(function(data){
$("#form-apply").prepend("<div class='alert alert-danger'>" + data.errors + "</div>");
console.log(data.errors);
});
});
HTML NOTE THIS MODULE IS A PHP INCLUDE CALLED 'CAREER-MODAL.PHP WHICH EXISTS IN THE 'INCLUDES' DIRECTORY.
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title center" id="myModalLabel">Career Application</h4>
</div>
<div class="modal-body">
<form id="form-apply" role="form" method="POST" action="includes/form-apply.php">
<div class="row">
<div class="col-md-6">
<div class="form-group name-group">
<label for="name">Full Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Full Name" tabindex="1" required="required">
</div>
</div>
<div class="col-md-6">
<div class="form-group email-group">
<label for="name">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email Address" tabindex="2" required="required">
</div>
</div>
</div>
<div class="form-group .message-group">
<label for="name">Summary of Background</label>
<textarea name="message" id="message" class="form-control" placeholder="Message" tabindex="3" required="required"></textarea>
</div>
<div class="form-group">
<label for="name">Upload Resume</label>
<input type="file" name="upload" id="upload" class="form-control" placeholder="No File Chosen" tabindex="4">
</div>
<div class="row center">
<button class="btn btn-secondary" tabindex="4">submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
Related
I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});
I have this exact code on another website and it works flawlessly but for some reason on this website it won't work. It sends the email but it refreshes the page and forwards it to a contact.php with a message.
I have read through everything I could find. I have gone over the code and nothing is different. I even changed the html button type from submit to button. Nothing is working. The last thing I tried was to copy and paste the code from the working website to this site, and still it refreshes the page.
The ajax codes is being loaded after the jquery.
html (index.html):
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages">
</div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">First Name *</label>
<input id="form_name" type="text" name="name" class="form-control" required="required"
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Last Name *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" required="required"
data-error="Lastname is required.">
<div class="help-block with-errors">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" required="required"
data-error="Valid email is required.">
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control">
<div class="help-block with-errors">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" rows="4" required="required"
data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-send" value="Send message">
</div>
</div>
</div>
</form>
php (contact.php)
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'Demo contact form <info#testing.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <info#testing.com>';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
?>
ajax (contact.js)
$(function () {
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
my javascript files are in the following order:
<script src="js/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
crossorigin="anonymous"></script>
<script type="text/javascript" src="./js/mdb.min.js"></script>
<!--validator-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
<!--contact.js-->
<script src="contact.js"></script>
Take out these changes:
Contact.php
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type:application/json');
echo $encoded;
exit();
}
After echoing your json encoded array, it is important that you exit() the script else you won't end up with a proper JSON string on the client side;.
Contact.js
<script>
$(document).ready(function () {
$('.btn-send').on('click', function (e) {
e.preventDefault();
$('#contact-form').validator(); //Just make sure this works because I didn't work with it.
let url = "contact.php";
let formData = $("#contact-form").serialize();
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: formData, //You shouldn't use `this` inside this ajax scope if you are trying to refer to your form. It's better you call the form element by it's `id` here or reassign `this` before entering the ajax call scope.
success: function (data) {
// we recieve the type of the message: success x danger and apply it to the
let messageAlert = 'alert-' + data.type;
let messageText = data.message;
// let's compose Bootstrap alert box HTML
let alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
})
});
</script>
index.html
Everything thing is fine here. Just edit these lines:
<form id="contact-form" method="post" role="form">
<div class="col-md-12">
<input type="button" class="btn btn-send" value="Send message">
</div>
i have html, js and php files for contact form, but for some reason form is not responding and not sending emails.
I would appreciate your help.
JS/HTML
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_company = $('input[name=company-name]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userCompany': user_company,
'userSubject': user_subject,
'userMessage': user_message
};
// Ajax post data to server
$.post('/php/contact-me.php', post_data, function(response) {
// Load json data from server and output message
if (response.type == 'error') {
output = '<div class="error-message"><p>' + response.text + '</p></div>';
} else {
output = '<div class="success-message"><p>' + response.text + '</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Your Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Your Email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Email'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Company name -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="company" class="form form-control" placeholder="Company name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Company name'" name="company-name" data-name="Company Name">
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area"
required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message ></button>
</form>
and here is php file
<?php
if($_POST) {
$to_Email = "email#gmyemail; // Write your email here
// Use PHP To Detect An Ajax Request
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
// Exit script for the JSON data
$output = json_encode(
array(
'type'=> 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
// Checking if the $_POST vars well provided, Exit if there is one missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userSubject"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Input fields are empty!'));
die($output);
}
// PHP validation for the fields required
if(empty($_POST["userName"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> We are sorry but your name is too short or not specified.'));
die($output);
}
if(!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Please enter a valid email address.'));
die($output);
}
// PHP validation for the fields required
if(empty($_POST["userCompany"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> We are sorry but your name is too short or not specified.'));
die($output);
}
// To avoid the spammy bots, you can change the value of the minimum characters required. Here it's <20
if(strlen($_POST["userMessage"])<20) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Too short message! Take your time and write a few words.'));
die($output);
}
// Proceed with PHP email
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
$headers .= 'From: My website' . "\r\n";
$headers .= 'Reply-To: '.$_POST["userEmail"]."\r\n";
'X-Mailer: PHP/' . phpversion();
// Body of the Email received in your Mailbox
$emailcontent = 'Hey! You have received a new message from the visitor <strong>'.$_POST["userName"].'</strong><br/><br/>'. "\r\n" .
'His message: <br/> <em>'.$_POST["userMessage"].'</em><br/><br/>'. "\r\n" .
'<strong>Feel free to contact '.$_POST["userName"].' via email at : '.$_POST["userEmail"].'</strong>' . "\r\n" ;
$Mailsending = #mail($to_Email, $_POST["userSubject"], $emailcontent, $headers);
if(!$Mailsending) {
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Oops! Looks like something went wrong, please check your information one more time.'));
die($output);
} else {
$output = json_encode(array('type'=>'message', 'text' => '<i class="icon ion-checkmark-round"></i> Hello '.$_POST["userName"] .', Your message has been sent, we will get back to you asap !'));
die($output);
}
}
?>
If I add jQuery and change to .on("submit" of the form, it works.
$(document).ready(function() {
$("#contact-form").on("submit",function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_company = $('input[name=company-name]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {
'userName': user_name,
'userEmail': user_email,
'userCompany': user_company,
'userSubject': user_subject,
'userMessage': user_message
};
// Ajax post data to server
$.post('/php/contact-me.php', post_data, function(response) {
// Load json data from server and output message
if (response.type == 'error') {
output = '<div class="error-message"><p>' + response.text + '</p></div>';
} else {
output = '<div class="success-message"><p>' + response.text + '</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Your Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Your Email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your Email'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Company name -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="company" class="form form-control" placeholder="Company name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Company name'" name="company-name" data-name="Company Name">
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area"
required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message ></button>
</form>
It seems you have a syntax error in your PHP code
$to_Email = "email#gmyemail; // Write your email here
It should change to $to_Email = "email#gmyemail"; // Write your email here
BTW, if it's not the issue, Please enable PHP debug mode and check the error logs. This may help you to find the issue.
I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.
PHP
<?php
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "description" => true, "email" => true, "number" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
//header('Content-type: application/json');
//attempt to send email
$messageBody = constructMessageBody();
require 'php_mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress("example#example.com");
$mail->Subject = $_POST['name'];
$mail->Body = $messageBody;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted from PHP.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
(function($) {
$('#form').on('submit', function(){
event.preventDefault();
var contactFormUtils = {
clearForm: function () {
grecaptcha.reset();
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").append('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$('#submit-email').prop('disabled', true).html("sending");
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log('success');
$('#form').fadeOut(400)
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
console.log('error');
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
$('#submit-report').prop('disabled', false).html("Send message");
contactFormUtils.clearForm();
},
complete: function() {
console.log('complete');
}
});
return false;
});
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8 site-block">
<form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
<div id="feedbackSubmit"></div>
</div>
change
jQuery('#form').on('submit', function(){
to
jQuery('.ajax').on('submit', function(event){
and replace ALL $ with jQuery
and
wrap your code in document ready function
jQuery(function(){});
This is my Modal layout:
<div class="modal fade" id="myContact" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Send me a message</h3>
<div id="thanks"></div>
</div>
<div class="modal-body">
<form class="contact" name="contact">
<input type="text" name="name" class="form-control" placeholder="Your Name"><br>
<input type="email" name="email" class="form-control" placeholder="Your E-mail"><br>
<textarea name="message" class="form-control" placeholder="Enter a Message"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
</div>
And this is the Jquery Script:
$("input#submit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //process to mail
data: $('form.contact').serialize(),
success: function(msg){
$("#myContact").modal('hide'); //hide popup
$("#thanks").html(msg) //hide button and show thank you
},
error: function(){
alert("failure");
}
});
});
And the PHP process.php:
<?php
//add the recipient's address here
$myemail = 'test#mail.com';
//grab named inputs from html then post to #thanks
if (isset($_POST['name'])) {
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$message = strip_tags($_POST['message']);
echo "<class=\"alert alert-success\" >Your message has been !";
//generate email and send!
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}
?>
First of all, Hello to All i`m new here....
I have a question.. how can I do when i push Send my Modal to hide (but whit delay to see the alert-success message ) and to be reset...
now is working and send my email but does not close and reset..
Thx Elod !!
on success you can use reset to reset the form in the modal
use an id for the form like my_Contact
$('#my_contact').reset(); //to reset the form
delay the modal hide can use setTimeout
setTimeout(function() { $('#myContact').modal('hide'); }, 3000);