I am following a guide to build a bootstrap contact form and submit it through mail.php without having to reload the page using ajax. I am able to get the form to work up until I try implementing ajax. I get stuck because the instructions arent clear as to which code exactly needs to be replaced and where the new code is supposed to go. Here is a link to the guide I am following and the section I am stuck at:
Sending email without reloading page using AJAX
This is the site I am trying to get it to work on: CRANE TECH. NET
I am not so familiar with php so I'm thinking that is where I am messing it up at.
Here is the exact code I am using:
HTML
<section class="section">
<h2 class="section-heading text-muted h4 pt-4">Free Consultation</h2>
<!--CONTACT DESCRIPTION-->
<p class="section-description">Are you ready to turn your vision into a reality? Fill out the contact form below and a member of our team will get back to you as soon as possible. Let's bring your idea to life!</p>
<div class="row">
<div class="col-12">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row">
<!--NAME INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="* NAME" required>
<label for="name" class=""></label>
</div>
</div>
<!--EMAIL INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="email" name="email" class="form-control" placeholder="* EMAIL" required>
<label for="email" class=""></label>
</div>
</div>
</div>
<div class="row">
<!-- PHONE NUMBER INPUT -->
<div class="col-12">
<div class="md-form">
<input type="text" id="clientPhone" name="clientPhone" class="form-control" placeholder="PHONE" required>
<label for="phone number" class=""></label>
</div>
</div>
<!--SUBJECT INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="subject" name="subject" class="form-control" placeholder="* SUBJECT" required>
<label for="subject" class=""></label>
</div>
</div>
</div>
<div class="row">
<!--MESSAGE INPUT-->
<div class="col-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="3" class="form-control md-textarea" placeholder="* MESSAGE" required></textarea>
<label for="message"></label>
</div>
</div>
</div>
</form>
<!-- SUBMIT BUTTON -->
<div class=" col-3 offset-3 offset-md-4 mb-4">
<button class="btn btn-warning" onclick="validateForm()">Send <i class="fa fa-paper-plane ml-1"></i></button>
</div>
<div id="status" class="text-muted col-12 col-md-8 offset-md-2 my-1"></div>
</div>
JS
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
return false;
} else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(email)) {
document.getElementById('status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
return false;
}
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'clientPhone': $('input[name=clientPhone]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
document.getElementById('contact-form').submit();
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
}
MAIL.PHP
<?php
if(isset( $_POST['name']))
$name = $_POST['name'];
if(isset( $_POST['email']))
$email = $_POST['email'];
if(isset( $_POST['clientPhone']))
$clientPhone = $_POST['clientPhone'];
if(isset( $_POST['subject']))
$subject = $_POST['subject'];
if(isset( $_POST['message']))
$message = $_POST['message'];
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
// if ($name === ''){
// echo "Name cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($email === ''){
// echo "Email cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// } else {
// if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
// echo "Email format invalid.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// }
// if ($subject === ''){
// echo "Subject cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($message === ''){
// echo "Message cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
$content="From: $name \n Email: $email \n Phone #: $clientPhone \n Subject: $subject \n Message: $message";
$recipient = "support#crane-tech.net";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!', 'code' => 1));
exit();
?>
Main Issue
You main issue is that there is a missing semcolon (;) and the end of line 15 in the php code.
Other Issues
Your website is using JQuery Slim, $.ajax is not included in the slim version so you are getting an error due to that. To fix this just include the full JQuery or do the ajax without JQuery.
You may also want to get rid of this line:
document.getElementById('contact-form').submit();
because it is causing a redirect when you are already manually submitting your data.
You should remove these lines because you have already set them:
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
Unrelated note:
If you are already using JQuery, you should be using it - instead of doing this:
document.getElementById('status')
You should be using:
$('#status')
Related
I am currently facing an issue and I am unable to understand the error. I have been trying to resolve it for some time now but I am unable to figure out what is causing the problem. I have been looking online for solutions but I have not been able to find any that have worked for me. I am now reaching out for help online in hopes that someone can assist me in understanding and resolving the error. Any help would be greatly appreciated.
I am trying to send an email through JavaScript and PHP and it gives the following error:
'mobile is required Message is required'
Here is my PHP code:
<?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"];
}
//mobile
if (empty($_POST["mobile"])) {
$errorMSG = "mobile is required ";
} else {
$mobile = $_POST["mobile"];
}
//Design type
if (empty($_POST["Dtype"])) {
$errorMSG = "Design Type is required ";
} else {
$Dtype = $_POST["Dtype"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
// replace email to get from date
$EmailTo = "mail#mail.com";
$EmailTo1 = "mail#mail.com";
$Subject = "New Enquery On _____";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "mobile: ";
$Body .= $mobile;
$Body .= "\n";
$Body .= "Design Type: ";
$Body .= $Dtype;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
$success = mail($EmailTo1, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>`
I also have the script here:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
event.preventDefault();
submitForm();
}
});
function submitForm() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var mobile = $("#mobile").val();
var Dtype = $("#Dtype").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message + "&mobile=" + mobile + "&Dtype=" + Dtype,
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);
$('#msgSubmit').delay(2000).hide(0);
}
Also the important part of the form here:
<form id="contactForm" data-toggle="validator" class="shake" action="php/form-process.php" method="post">
<div class="row">
<div class="fieldsets col-sm-12">
<input type="text" id="name" placeholder="Enter name" required data-error="Please fill Out">
<div class="help-block with-errors"></div>
</div>
<div class="fieldsets col-sm-12">
<input type="email" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="fieldsets col-sm-12">
<input type="text" id="mobile" placeholder="Enter mobile" required data-error="Please fill Out">
<div class="help-block with-errors"></div>
</div>
<div class="fieldsets col-sm-12">
<select name="Dtype" id="Dtype" required>
<option value="">Select Requirement</option>
<option value="2BHK+2T">2BHK +2T</option>
<option value="3BHK+2T">3BHK +2T</option>
<option value="3BHK+3T">3BHK + 3T</option>
<option value="3BHK+3T+POOJA">3BHK + 3T +POOJA</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="fieldsets">
<textarea id="message" rows="4" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="btn lnk btn-main bg-btn">Submit <span class="circle"></span></button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
<p class="trm"><i class="fas fa-lock"></i>We hate spam, and we respect your privacy.</p>
</form>
I have tried to completely re-write my php script, my form and everything. I just can't seem to figure it out and it got me stressed so badly :(
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.
This question already has answers here:
(PHP) Stuck making submission form anti spam
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 3 years ago.
When I open the email the message is always empty, I get the name and email but message is empty,
I recently added google recaptcha v3 which was giant pain , but It is now working.
anyway I tried to debug this, and It show no errors, the message textarea send to email but I receive it empty...
this is the form
<?php
if(isset($_POST['submit'])){
$captcha=$_POST['token'];
$secret = 'censord';
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
);
// use json_decode to extract json response
$response = json_decode($response);
if($response->success == true) {
//save data to database
echo '<div class="alert alert-success">
<strong>Success!</strong> Data is saved.
</div>';
} else {
echo '<div class="alert alert-warning">
<strong>warning!</strong> Failed to save data.
</div>';
}
}
?>
<style>
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$name = htmlspecialchars(stripslashes(trim($_POST['username'])));
$email = htmlspecialchars(stripslashes(trim($_POST['email'])));
$text = htmlspecialchars(stripslashes(trim($_POST['textt'])));
if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
$name_error = 'Invalid name';
}
if(!preg_match("/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
$email_error = 'Invalid email';
}
if(strlen($text) === 0){
$message_error = 'Your message should not be empty';
}
if(preg_match('/http|www/i',$comments)) {
$error_message .= "We do not allow a url in the comment.<br />";
}
}
?>
<div id="container">
<div class="form-wrap">
<h1>Report bug</h1>
<p>Report us if you find any bug or broken link in our free online programming classes.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<div class="form-group">
<label for="username">Name:</label>
<input type="text" name="username">
<p><?php if(isset($name_error)) echo $name_error; ?></p>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email">
<p><?php if(isset($email_error)) echo $email_error; ?></p>
</div>
<div class="form-group">
<label for="textt">Message:</label>
<textarea type="text" name="textt" rows="22" cols="42"></textarea>
<p><?php if(isset($message_error)) echo $message_error; ?></p>
</div>
<button type="submit" name="submit" value="Submit" class="btn">Report us</button>
<input type="hidden" name="action" value="validate_captcha">
<?php
if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
$to = 'censord'; // edit here
$body = " Name: $name\n E-mail: $email\n Message:\n $message";
if(mail($to, $subject, $body)){
echo '<p style="color: green">Message sent</p>';
}else{
echo '<p>Error occurred, please try again later</p>';
}
}
?>
</form>
</div>
</div>
</body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('censord', {action: 'validate_captcha'}).then(function(token) {
console.log(token);
document.getElementById("token").value = token;
});
});
</script>
</html>
i am totally new to ajax and just started getting a hang of php. So i got a ajax and php email code online that seemed to work on the first try and next few days suddenly kept returning with the error message which is "something went wrong". Please i'd appreciate if i could be put through on the source of this and how i could fix it. Thanks much
JS
$("#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: "php/form-process.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);
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contactForm">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="Full Name" name="name" data-error="Please input your full name" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control" id="email" placeholder="Your Email" name="name" data-error="Please input your email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" id="message" placeholder="Your Message" rows="8" data-error="Write your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="submit-button text-center">
<button class="btn btn-common" id="submit" type="submit">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</div>
</div>
</div>
</form>
PHP
<?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"];
}
$EmailTo = "name#email.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 :("; //-->this is the error i get
} else {
echo $errorMSG;
}
}
?>
your logic is backwards, in your code an empty $errorMSG is good.
if($errorMSG != ""){ // if NOT empty
echo "Something went wrong: ".$errorMSG;
}else{
//good
}
I do not receive any emails when my webform is filled out. It does not give me any errors. Code posted below:
HTML form:
<div class="col-md-6">
<h3>General Questions? <p class="h4">Use our form.</p></h3>
<address>Required fields are marked with an *.</address>
<div class="col-md-12">
<form data-toggle="validator" role="form" class="form-horizontal" id="contactForm">
<!-- Name-->
<div class="form-group">
<label for="inputName" class="control-label"><span class="glyphicon glyphicon-user">
</span> Name * </label><input type="text" class="form-control" id="inputName"
placeholder="What's your name?" data-errors="We need to know what to call you!" required>
<div class="help-block with-errors"></div>
</div>
<!-- Email-->
<div class="form-group">
<label for="inputEmail" class="control-label"><span class="glyphicon glyphicon-
envelope"></span> Email *</label>
<input type="email" class="form-control" id="inputEmail" placeholder="example#example.com"
data-errors="This email address is invalid" required>
<div class="help-block with-errors"></div>
</div>
<!-- Phone Number-->
<div class="form-group">
<label for="inputNumber" class="control-label"><span class="glyphicon glyphicon-phone-
alt"></span> Phone Number</label>
<input type="text" class="form-control" id="inputNnumber" data-minlength="9"
placeholder="(123) 867-5309">
</div>
<!-- Textarea -->
<div class="form-group">
<label for="inputMessage" class="control-label"><span class="glyphicon glyphicon-pencil">
</span> Message *</label>
<textarea rows="8" class="form-control" placeholder="How can we help?" data-errors="We
can't help if you don't tell us how!" required>
</textarea>
<div class="help-block with-errors"></div>
</div>
<!-- Select Basic -->
<div class="control-group text-center">
<span><span class="glyphicon glyphicon-question-sign"></span> <strong>How should we
contact you?</strong></span><br>
<input type="radio" name="contact" value="phone"> by phone
<input type="radio" name="contact" value="email"> by email
</div>
<!-- Button -->
<br>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-sm btn-block">Submit</button>
</div>
</form>
</div>
</div>
Javacript: (it's at devnew.company.com/mail.php and will eventually be at company.com/mail.php. Am I correct in leaving it at /mail.php here?)
var mailUrl = "/mail.php";
var formId = "contactForm";
var completeHTML = ' <div class="alert alert-primary"> Sent! Thanks, we will be in touch
soon. </div> ';
function submitForm(){
$.ajax({
url : mailUrl,
type: 'post',
data:{
inputName : $('#inputName').val(),
inputEmail : $('#inputEmail').val(),
inputNumber : $('#inputNumber').val(),
inputMessage : $('#inputMessage').val(),
contact : $('input[name="contact"]:checked').val()
}
});
}
$(function(){
$('#contactForm').submit(function(){
submitForm();
$(this).html( completeHTML );
return false;
})
})
PHP
<?php
if (isset($_POST['Submit'])) {
if ($_POST['inputName'] != "") {
$_POST['inputName'] = filter_var($_POST['inputName'], FILTER_SANITIZE_STRING);
if ($_POST['inputName'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
if ($_POST['inputEmail'] != "") {
$email = filter_var($_POST['inputEmail'], FILTER_SANITIZE_EMAIL);
if (!filter_var($inputEmail, FILTER_VALIDATE_EMAIL)) {
$errors .= "$inputNumber is not a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
if ($_POST['inputNumber'] != "") {
$homepage = filter_var($_POST['inputNumber'], FILTER_SANITIZE_NUMBER_INT);
if ($_POST['inputNumber'] == "") {
$errors .= "Please enter 9 digits.<br/><br/>";
}
} else {
$errors .= 'Please enter your phone number.<br/>';
}
if ($_POST['inputMessage'] != "") {
$_POST['inputMessage'] = filter_var($_POST['inputMessage'],
FILTER_SANITIZE_STRING);
if ($_POST['inputMessage'] == "") {
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
if ($_POST['radio'] != "") {
$_POST['radio'] = filter_var($_POST['radio'], FILTER_SANITIZE_STRING);
if ($_POST['inputName'] == "") {
$errors .= 'Please choose an option.<br/><br/>';
}
} else {
$errors .= 'Please choose one.<br/>';
}
if (!$errors) {
$mail_to = 'rnunley#remedypartners.com';
$subject = 'New Mail from Form Submission';
$message = 'From: ' . $_POST['inputName'] . "\n";
$message .= 'Email: ' . $_POST['inputEmail'] . "\n";
$message .= 'Homepage: ' . $_POST['inputNumber'] . "\n";
$message .= "Message:\n" . $_POST['inputMessage'] . "\n\n";
$message .= 'Contact choice: ' . $_POST['radio'] . "\n";
mail($to, $subject, $message);
echo "Thank you for your email, we'll be in touch!<br/><br/>";
} else {
echo '<div style="color: red">' . $errors . '<br/></div>';
}
}
?>
From your code, it doesn't look like you are sending a Submit variable in your ajax data. If that is the case, then your PHP will fail your initial if statement. You could try to add a print_r($_POST); at the beginning of your PHP and then watch the browser console to see what PHP is receiving.
It could be that your javascript thinks that the variables you are trying to pass are being read as non existent javascript vars
below is what maybe could work
$.ajax({
url : mailUrl,
type: 'post',
data:{
"inputName" : $('#inputName').val(),
"inputEmail" : $('#inputEmail').val(),
"inputNumber" : $('#inputNumber').val(),
"inputMessage" : $('#inputMessage').val(),
"Submit" : "TRUE",
"contact" : $('input[name="contact"]:checked').val()
},success: function (data) {
alert(data);
}
});
and add this on the beginning of your mail.php
foreach($_POST as $key => $value){
$content .= $key.' : '.$value;
}
echo $content
Too see what you are recieving on your mailurl