I have this contact form and I'm trying to use jQuery/AJAX and PHP to have the field input values sent to me via email. Well, the email sends to me just fine, but without any of the field input. The email is just the $to and the $subject of the PHP mail() function. Please see code below. Any ideas, critiques, or suggestions are welcome. Thanks for your help!
$(document).ready(function() {
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
//var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$("button").click(function(e) {
// Stop the browser from submitting the form.
e.preventDefault(e);
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
success: function(result){
$('#contact-name').val('');
$('#contact-email').val('');
$('#contact-website').val('');
$('#contact-message').val('');
},
error: function(xhr,status,error){
}
});
});
});
});
<?php
require_once 'swiftmailer/lib/swift_required.php';
//Swift Mailer script
$filter = FILTER_SANITIZE_STRING;
//Grab POST Data
$name = filter_var($_POST['contact-name'], $filter);
$email = filter_var($_POST['contact-email'], FILTER_SANITIZE_EMAIL);
$website = filter_var($_POST['contact-website'], FILTER_SANITIZE_URL);
$message = filter_var($_POST['contact-message'], $filter);
//Create email body
$body = "Name: " . $name . "<br />" . "Email: " . $email . "<br />" . "Website: " . $website . "<br />" . "Message: " . $message;
//Create Transport
$transport = Swift_SmtpTransport::newInstance("host", "port", "security")
->setUsername("username")
->setPassword("password");
//Create Mailer
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('New Form')
->setFrom(array("email" => "Lead from Contact form"))
->setTo(array('email', 'email' => 'Recipients'))
->setSubject('You have a new message!')
->setBody($body, 'text/html');
//Send Message
$result = $mailer->send($message);
if ($result) {
// Set a 200 (okay) response code. //http_response_code(200); echo "Thank You! Your message has been sent."; } else { // Set a 500 (internal server error) response code. //http_response_code(500); echo "Oops! Something went wrong and we couldn't send your message."; }
?>