I'm new in ajax/js/php.
I have a small contact form
<form id="contact-form" method="post" action="process.php" role="form">
<div class="messages"></div>
<div class="form-group">
<label for="form_name">First name *</label>
<input id="form_firstname" type="text" name="name" class="form-control" placeholder="Please enter your first name *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_lastname">Last name *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your last name *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
<p><strong>*</strong> These fields are required.</p>
</form>
<button type="submit" class="btn btn-info" value="Create Account">Create Account</button>
with small js and php
script.js
$("#contact-form").submit(function(event) {
// cancels the form submission
"use strict";
event.preventDefault();
submitForm();
});
function submitForm() {
// Initiate Variables With Form Content
"use strict";
var firstname = $("#form_firstname").val();
var lastname = $("#form_lastname").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.ajax({
type: "POST",
url: "process.php",
data: "name=" + firstname + lastname + "&email=" + email + "&phone=" + phone,
});
}
process.php
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$EmailTo = "name#email.com";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
} else {
echo "invalid";
}
?>
for some reason it's not working on way I would like to, not sending me emails (i know to put my email in $Emailto).
Often I was using only php form but I would like to avoid reloading page. I try to understand where I'm making error.
$('#contact-form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "process.php",
data:$(this).serialize(), //get form values
}).done(function(data){
console.log(data); // will contain success or invalid
});
});
Change your submit function to:
$(document).ready(function() {
$("#contact-form").submit(function(event){
"use strict";
event.preventDefault(); // cancels the form submission
var firstname = $("#form_firstname").val();
var lastname = $("#form_lastname").val();
var email = $("#form_email").val();
var phone = $("#form_phone").val();
$.ajax({
type: "POST",
url: "process.php",
data: {
name: firstname + lastname, //or firstname + " " + lastname if you want the first and lastname to be separated by a space
email: email,
phone: phone
}
}).done(function(data){
console.log(data); // will contain success or invalid
});
});
});
The values you were trying to get for email and phone were not properly defined (they were lacking the form_).
And you cannot use a querystring with a POST type only when using a GET type.
Related
I should solve a problem with a contact form and I don't know where to put my hands anymore.
I have a form in HTML, then a validation in JS and finally an email sending in PHP.
The form data are: Name, Clinic, Email, Phone, Address and Valutation.
In the email I receive the data are:
Name: name entered in the form
Email: email entered in the form
Clinic: undefined
Phone: undefined
Address: undefined
Valutation: undefined
This is the code (HTML + JS):
// JavaScript Document
$(document).ready(function() {
"use strict";
$(".contact-form").submit(function(e) {
e.preventDefault();
var name = $(".name");
var email = $(".email");
var clinic = $(".clinic");
var phone = $(".phone");
var address = $(".address");
var valutation = $(".valutation");
var subject = $(".subject");
var msg = $(".message");
var flag = false;
if (name.val() == "") {
name.closest(".form-control").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".form-control").removeClass("error").addClass("success");
}
if (email.val() == "") {
email.closest(".form-control").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".form-control").removeClass("error").addClass("success");
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&subject=" + subject.val() + "&msg=" + msg.val() + "&clinic=" + clinic.val() + "&phone=" + phone.val() + "&address=" + address.val() + "&valutation=" + valutation.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "php/contactForm.php",
cache: false,
success: function(d) {
$(".form-control").removeClass("success");
if (d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="#48af4b">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="#ff5607">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").on('click', function() {
$(".form-control").removeClass("success").removeClass("error");
});
})
<div class="row justify-content-center">
<div class="col-lg-10 col-xl-8">
<div class="form-holder">
<form class="row contact-form" method="POST" action="php/contactForm.php" id="contactForm">
<!-- Form Select -->
<div class="col-md-12 input-subject">
<p class="p-lg">This question is about: </p>
<span>How satisfied are you with the service that Lab offers? </span>
<select class="form-select subject" aria-label="Default select example" name="valutation">
<option>Very unsatisfied</option>
<option>Unsatisfied</option>
<option>Satisfied</option>
<option>Very satisfied</option>
<option selected>I don't have an opinion</option>
</select>
</div>
<!-- Contact Form Input -->
<div class="col-md-12">
<p class="p-lg">Your Name: </p>
<span>Please enter your Dentist Name: </span>
<input type="text" name="name" class="form-control name" placeholder="Your Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Clinic Name: </p>
<span>Please enter your Clinic Name: </span>
<input type="text" name="clinic" class="form-control name" placeholder="Clinic Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Your Email Address: </p>
<span>Please carefully check your email address for accuracy</span>
<input type="text" name="email" class="form-control email" placeholder="Email Address*">
</div>
<div class="col-md-12">
<p class="p-lg">Phone Number: </p>
<span>Please enter your/clinic phone number: </span>
<input type="text" name="phone" class="form-control name" placeholder="Phone Number*">
</div>
<div class="col-md-12">
<p class="p-lg">Address: </p>
<span>Please enter Clinic Address: </span>
<input type="text" name="address" class="form-control name" placeholder="Address*">
</div>
<!-- Contact Form Button -->
<div class="col-md-12 mt-15 form-btn text-right">
<button type="submit" class="btn btn-skyblue tra-grey-hover submit">Submit Request</button>
</div>
<!-- Contact Form Message -->
<div class="col-lg-12 contact-form-msg">
<span class="loading"></span>
</div>
</form>
</div>
</div>
</div>
And this is the PHP code:
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$clinic = $_REQUEST["clinic"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$valutation = $_REQUEST["valutation"];
$to = "myemail#email.com";
if (isset($email) && isset($name)) {
$email_subject = "Request to access to the Price List";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: $name<br/> Email: $email <br/> Clinic: $clinic <br/> Phone: $phone <br/> Address: $address <br/> Valutation: $valutation";
$mail = mail($to, $email_subject, $msg, $headers);
if ($mail) {
echo 'success';
} else {
echo 'failed';
}
}
?>
Your issue is your selectors. You only use classes name and email for all your inputs.
<input type="text" name="phone" class="form-control name" ...>
should actually be:
<input type="text" name="phone" class="form-control phone" ...>
and so on for all the other inputs. Change your selectors to the appropriate classNames.
Also, never just use i.e: $(".name");, $(".email"); etc. as your selectors. As you know already $(".name"); will get every class="name" in your document. Same goes for all the other selectors. Instead, use the second argument (ParentElement) that will limit the search only to the children elements of the provided parent:
var name = $(".name", this);
or rather, use attribute selectors like:
var clinic = $(`[name="clinic"]`, this);
IMPORTANT NOTE about validation:
never trust the client.
JS validation should be used minimally, just as a UX tool to help, inform the user about basic errors/typos. The real validation, as well as all the related error responses, should be handled on the backend side.
Currently your PHP seems quite open to XSS attacks.
You don't need a HTML <form> in order to send data to the server. All it takes to an attacker is to find your route/path (usually exposed via the form's action attribute), take a look at the names in the source and manually construct a HTTP request, and send dangerous arbitrary data to your server. Just so you keep in mind.
I have a contact section in my website. I want when a user submit the form all the data should be sent in email plus the page don't reload.
My form:
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" id="name" >
</div>
<div class="form-group">
<label for="email">E-Mail:</label>
<input type="email" class="form-control" name="email" id="email" >
</div>
<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="text" class="form-control" name="mobile" id="mobile">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="5" name="message" id="message"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary" style="width: 100%" name="form_submit">Send Message</button>
Javascript
$(document).ready(function(){
$('#send').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var message = $('#message').val();
var varData = 'name=' + name + '&email=' + email + '&mobile=' + mobile + '&message=' + message;
$.ajax({
type: 'POST',
url: 'process.php',
data: varData,
success: function() {
alert("message sent");
}
});
});
});
</script>
Process.php
if (isset( $_POST['form_submit'] ) ) {
// Do processing here.
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$message = $_POST['message'];
if ($name == '' || $email == '' || $mobile=='' || $message=='')
{
echo "<script> alert('please fill the field');
</script>";
exit;
}
elseif ($_POST["email"]<>'') {
$ToEmail = 'email#gmail.com';
$EmailSubject = 'Website Contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br><br>";
$MESSAGE_BODY .= "email: ".$_POST["email"]."<br>";
$MESSAGE_BODY .= "mobile: ".nl2br($_POST["mobile"])."<br>";
$MESSAGE_BODY .= "message: ".nl2br($_POST["message"])."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
echo "<script> alert('mail sent')
</script>";
exit;
} else{
echo "<script> alert ('there is some problem');</script>";
};
}
?>
The problem is the form is not using the code mentioned in "process.php"
How can I ensure the form data is sent in email? I have searched the previous answers but couldn't fix this.
I am trying to add one more input (called servizio) in this contact form but on submit I get an error message in the console 'Uncaught ReferenceError: servzio is not defined' even if it is defined in both JS and PHP file.
Can you please recognise if I am doing something wrong? Thanks in advance for your help
File contact.js
(function($){
$(document).ready(function() {
/* ---------------------------------------------- /*
* Contact form ajax
/* ---------------------------------------------- */
$('#contact-form').find('input,textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault();
var submit = $('#contact-form submit');
var ajaxResponse = $('#contact-response');
var name = $("input#cname").val();
var email = $("input#cemail").val();
var servizio = $("input#cservizio").val();
var message = $("textarea#cmessage").val();
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
dataType: 'json',
data: {
name: name,
email: email,
servzio: servzio,
message: message,
},
cache: false,
beforeSend: function(result) {
submit.empty();
submit.append('<i class="fa fa-cog fa-spin"></i> Wait...');
},
success: function(result) {
if(result.sendstatus == 1) {
ajaxResponse.html(result.message);
$form.fadeOut(500);
} else {
ajaxResponse.html(result.message);
}
}
});
}
});
});
This is the File contact.php
<?php
// Mail settings
$to = "emiliano#dsasa.agency";
$subject = "asdsa's";
// You can put here your email
$header = "From: emiliano#dsadsa.agency\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/plain; charset=utf-8\r\n";
$header.= "X-Priority: 1\r\n";
if ( isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["servizio"]) && isset($_POST["message"])) {
$content = "Name: " . $_POST["name"] . "\r\n";
$content .= "Email: " . $_POST["email"] . "\r\n";
$content .= "servizio: " . $_POST["servizio"]; . "\r\n"
$content .= "Message: " . "\r\n" . $_POST["message"];
if (mail($to, $subject, $content, $header)) {
$result = array(
"message" => "Thanks for contacting us.",
"sendstatus" => 1
);
echo json_encode($result);
} else {
$result = array(
"message" => "Sorry, something is wrong.",
"sendstatus" => 0
);
echo json_encode($result);
}
}
?>
This is the html
<form id="contact-form" role="form" novalidate="">
<div class="form-group">
<label class="sr-only" for="cname">Name</label>
<input type="text" id="cname" class="form-control" name="cname" placeholder="Name*" required="" data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<label class="sr-only" for="cservizio">1 Servizio Video o 2 Servizio Foto</label>
<input type="text" id="cservizio" name="cservizio" class="form-control" placeholder="Indica il numero corrispondente al servizio">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<label class="sr-only" for="cemail">Your Email</label>
<input type="email" id="cemail" name="cemail" class="form-control" placeholder="Your E-mail*" required="" data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<textarea class="form-control" id="cmessage" name="cmessage" rows="7" placeholder="Message*" required="" data-validation-required-message="Please enter your message."></textarea>
<p class="help-block text-danger"></p>
</div>
<div class="text-center">
<button type="submit" class="btn btn-block btn-round btn-d">Submit</button>
</div>
</form>
<!-- Ajax response -->
<div id="contact-response" class="ajax-response font-alt"></div>
I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
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 {
echo $responseArray;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
I have a contact form on a landing page that I want to send through with AJAX & PHP but for some reason, the variables are not passing. I am getting the email but the variables are blank. You can go to removed to see the text site, it's not set up with the database on this site though, so if you try to click through nothing will happen.
Does anyone have any idea what could be causing my form to not cooperate?
The HTML
<form role="form" id="form" name="form" action="submit.php" method="post">
<div class="form-group has-feedback">
<input type="text" class="form-control input-lg" id="name" name="name" placeholder="Full Name" />
<span class="help-block" style="display: none;">Please enter your full name.</span>
</div>
<div class="form-group has-feedback">
<input type="tel" class="form-control input-lg optional" id="phone" name="phone" placeholder="Phone (Optional)"/>
<span class="help-block" style="display: none;">Please enter a valid phone number.</span>
</div>
<div class="form-group has-feedback">
<input type="email" class="form-control input-lg" id="email" name="email" placeholder="Email" />
<span class="help-block" style="display: none;">Please enter a valid email address.</span>
</div>
<div class="form-group has-feedback">
<textarea rows="5" cols="30" class="form-control input-lg" id="message" name="message" placeholder="Message" ></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group has-feedback">
<label>
<input type="checkbox" class="form-control input-sm optional" id="newsletter" name="newsletter" checked="checked">
Opt-in to our newsletters to stay up-to-date with the latest information. </label>
<span class="help-block" style="display: none;">Would you like to sign up for our newsletter?</span>
</div>
<div class="form-group has-feedback">
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg pull-right" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Submit</button>
</div>
</form>
The Script
//*Form*//
$('document').ready(function(){
$('#form').validate({
rules:{
"name":{
required:true,
maxlength:40
},
"phone":{
required:false
},
"email":{
required:true,
email:true,
maxlength:100
},
"message":{
required:false
},
"newsletter":{
required:false
}},
messages:{
"name":{
required:"This field is required"
},
"phone":{
required:"This field is required"
},
"email":{
required:"This field is required",
email:"Please enter a valid email address"
},
"message":{
required:"This field is required"
},
"newsletter":{
required:"This field is required"
}},
submitHandler: function(form){
$.ajax ({
type: "POST",
url: "submit.php",
dataType: "json",
data:{"name":$("#name").text(),"phone":$("#phone").text(),"email":$("#email").text(),"message":$("message").text(),"newsletter":$("#newsletter").checked},
target: '#preview',
success: function(Result) {
alert(Result[0]);
$('#formbox').slideUp('fast');
$('#success').html();
$('#success').show();
},
failure: function (arg1, arg2) {
alert(arg1 + '\n\n' + arg2);
},
error: function (Result, Error, arg3, arg4) {
alert(Result + '\n\n' + Error + '\n\n' + arg3 + '\n\n' + arg4);
}
});
}
});
});
</script>
The PHP
<?php
require_once 'db.php';
header('Content-Type: application/json');
/*
$checkemail = $_POST['email'];
if (filter_var($checkemail, FILTER_VALIDATE_EMAIL)) { echo ""; }
else { die ("Invalid email, form processing has not completed.");
}
*/
// check email validity. clean name, phone, and message.
$name = htmlspecialchars(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$phone = htmlspecialchars(filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING));
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$newsletter = htmlspecialchars(filter_input(INPUT_POST, 'newsletter', FILTER_SANITIZE_STRING));
// commit to database
require_once 'db.php';
$stmt = $pdo->prepare("INSERT INTO contact (name, phone, email, message, newsletter) VALUES (?,?,?,?,?)");
$stmt->bindParam(1, $name, PDO::PARAM_STR, 50);
$stmt->bindParam(3, $phone, PDO::PARAM_STR, 50);
$stmt->bindParam(2, $email, PDO::PARAM_STR, 50);
$stmt->bindParam(4, $message);
$stmt->bindParam(5, $newsletter, PDO::PARAM_STR, 64);
$pdo->beginTransaction();
$stmt->execute();
$pdo->commit();
//form email
$today = date("Y-m-j");
$body = "";
$body .= "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Phone: $phone\n";
$body .= "Message: $message\n";
$body .= "Newsletter: $newsletter\n";
//send email 'change me to clients address'
mail("angela#etvsoftware.com","Dogwood Hills Gun Club Contact Form",$body,"angela#etvsoftware.com");
$stmt = null;
$pdo = null;
#What we say when everything goes right
$result = array(
"message" => "Your message has been sent. We will respond to you as soon as possible."
);
print json_encode($result);
?>
Instead of:
data:{"name":$("#name").text(),"phone":$("#phone").text(),"email":$("#email").text(),"message":$("message").text(),"newsletter":$("#newsletter").checked}
You should consider something cleaner and more flexible using serialize() like that:
data: $('#form').serialize()
This will send all the form fields in the POST request with your ajax call. If this is not working, Please try to var_dump($_POST) to make sure what you are getting.