I cannot get my webform to send (php, javascript) - javascript

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

Related

Html and php form not submitting issue

Hi guys I have been having trouble with one of the websites using HTML and PHP
The form doesn't seem to submit or send a message. Attached is the code please any help will be great. Also, the PHP and javascript have been attached for reference.
Also sometimes the page doesn't respond to the button.
If anyone can fix the code will be great.
CONTACT FORM
/*-----------------------------------------------------------------------------------*/
function checkmail(input) {
var pattern1 = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (pattern1.test(input)) {
return true;
} else {
return false;
}
}
function proceed() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var phone = document.getElementById("phone");
var movingfrom = document.getElementById("movingfrom");
var movingto = document.getElementById("movingto");
var date = document.getElementById("date");
var msg = document.getElementById("message");
var errors = "";
if (name.value == "") {
name.className = 'error';
return false;
} else if (email.value == "") {
email.className = 'error';
return false;
} else if (checkmail(email.value) == false) {
alert('Please provide a valid email address.');
return false;
} else if (phone.value == "") {
phone.className = 'error';
return false;
} else if (movingfrom.value == "") {
movingfrom.className = 'error';
return false;
} else if (movingto.value == "") {
movingto.className = 'error';
return false;
} else if (date.value == "") {
date.className = 'error';
return false;
} else if (msg.value == "") {
msg.className = 'error';
return false;
} else {
$.ajax({
type: "POST",
url: "php/submit.php",
data: $("#contact_form").serialize(),
success: function(msg) {
//alert(msg);
if (msg) {
$('#contact_form').fadeOut(1000);
$('#contact_message').fadeIn(1000);
document.getElementById("contact_message");
return true;
}
}
});
}
};
<div class="contact-form">
<!-- Form -->
<div class="margin-top-50">
<div class="contact-form">
<!-- Success Msg -->
<div id="contact_message" class="success-msg"> <i class="fa fa-paper-plane-o"></i>Thank You. Your Message has been Submitted</div>
<!-- FORM -->
<form id="contact_form" class="contact-form" method="post" action="php/submit.php" onsubmit="return ValidateForm()">
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="email" id="email" placeholder="E-Mail">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="phone" id="phone" placeholder="Phone Number">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="movingfrom" id="movingfrom" placeholder="Moving From">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="movingto" id="movingto" placeholder="Moving To">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="date" class="form-control" name="date" id="date" placeholder="Date">
</label>
</li>
<li class="col-sm-12">
<label>
<select class="form-control" id="typeofmove" placeholder="Date Of Move" required>
<option>Move Type</option>
<option>Residential Move</option>
<option>Office Move</option>
<option>Inter-City Move</option>
<option>Piano Move</option>
<option>Spa-Pool Move</option>
<option>Pool Table Move</option>
<option>Loading & Unloading Only</option>
<option>Packing</option>
<option>Assembly</option>
<option>TradeMe Pickups</option>
<option>Commercial Delivery</option>
<option>Packaging Material</option>
</select>
</label>
</li>
<li class="col-sm-12">
<label>
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Your Message"></textarea>
</label>
</li>
<li class="col-sm-12">
<button type="submit" value="submit" class="btn" id="btn_submit" onClick="proceed();">Submit</button>
</li>
</ul>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-4 col-sm-5 col-xs-12">
SUBMIT.PHP /*-----------------------------------------------------------------------------------*/
<?php
// specify your email here
$to = 'testmail#gmail.com';
// Assigning data from $_POST array to variables
if (isset($_POST['name'])) { $name = $_POST['name']; }
if (isset($_POST['phone'])) { $name = $_POST['phone']; }
if (isset($_POST['email'])) { $from = $_POST['email']; }
if (isset($_POST['movingfrom'])) { $name = $_POST['movingfrom']; }
if (isset($_POST['movingto'])) { $name = $_POST['movingto']; }
if (isset($_POST['date'])) { $name = $_POST['date']; }
if (isset($_POST['typeofmove'])) { $name = $_POST['typeofmove']; }
if (isset($_POST['message'])) { $message = $_POST['message']; }
// Construct subject of the email
$subject = 'Booking Enquiry ' . $name;
// Construct email body
$body_message .= 'Name: ' . $name . "\r\n";
$body_message .= 'Email: ' . $from . "\r\n";
$body_message .= 'Phone: ' . $phone . "\r\n";
$body_message .= 'Moving From: ' . $movingfrom . "\r\n";
$body_message .= 'Moving To: ' . $movingto . "\r\n";
$body_message .= 'Date Of Move: ' . $date . "\r\n";
$body_message .= 'Message: ' . $message . "\r\n";
// Construct headers of the message
$headers = 'From: ' . $from . "\r\n";
$headers .= 'Reply-To: ' . $from . "\r\n";
$mail_sent = mail($to, $subject, $body_message, $headers);
if ($mail_sent == true){ ?>
<script language="javascript" type="text/javascript">
window.alert("Sent Successfuly.");
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
window.alert("Error! Please Try Again Later.");
</script>
<?php
} // End else
?>
First of all you can try check your url.Is it correct or no.For example send anything via ajax and show the response at console log.If it is not working thats mean your url is wrong.

Send Form data in Email using PHP without refreshing the page

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.

PHP Contact Form Won't Submit Properly

I got my simple PHP contact form working on my website over at
http://www.colin-grant.ca/speedvale
but when I migrated my contact form to http://www.speedvale.com, it gives me the error 'something went wrong :('.
I have posted my code below for you to see, any help would be great - as I'm not the best at PHP.
HTML
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-12 mx-auto">
<div class="row">
<div class="col-sm-12 col-sm-offset-3">
<div class="well">
<h1>Contact Us</h1>
<p class="text-center">We are always interested in hearing about how we can improve your visit. If you need more information regarding our packages, or if you wish to set up a detailing appointment, toss us a message below and we will get back to you ASAP.</p>
<hr>
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="fname" class="h4">First Name</label>
<input type="text" class="form-control" id="fname" placeholder="Please enter your First Name" required data-error="Please Enter First Name">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="lname" class="h4">Last Name</label>
<input type="text" class="form-control" id="lname" placeholder="Please enter your Last Name" required data-error="Please Enter Last Name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="text" class="form-control" id="email" placeholder="Whats your e-mail?" required data-error="Please enter email">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="phone" class="p">Phone</label>
<input type="text" class="form-control" id="phone" placeholder="Whats your phone number?" required data-error="Please enter Phone Number">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-12">
<label for="email" class="h4">Service</label>
<select class="form-control" id="service" placeholder="Service"name="services">
<option value="" selected disabled>Please choose a service</option>
<option value="Gold Package ($79.99 / $99.99)">Gold Package ($79.99 / $99.99)</option>
<option value="Platinum 1 Package ($144.99 / $174.99)">Platinum 1 Package ($144.99 / $174.99)</option>
<option value="Platinum 2 Package ($199.99 / $229.99)">Platinum 2 Package ($199.99 / $229.99) </option>
<option value="VIP Package ($329.99 / $359.99)">VIP Package ($329.99 / $359.99)</option>
<option value="Express Package ($29.99 / $39.99)">Express Package ($29.99 / $39.99)</option>
<option value="Interior Package ($119.99 / $139.99)">Interior Package ($119.99 / $139.99)</option>
<option value="Exterior Package ($84.99 / $134.99)">Exterior Package ($84.99 / $134.99)</option>
<option value="Additional Services">Additional Services</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="p ">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Please leave details here about the make and model of your car, and any additional information we can use to make your apppointment or request better! Thank you" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button style="width:100%; padding: 10px; margin-bottom: 20px;" type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Submit</button>
<p class="text-center" style="font-size: 14px;">Please do your best to fill out the form below with as much information as possible so we can get started right away on your inquiry!</p>
<p class="text-center" style="font-size:14px;">Thank you from all of us here at Speedvale Auto Detailing.</p>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
PHP
<?php
$errorMSG = "";
// FIRST NAME
if (empty($_POST["fname"])) {
$errorMSG = "First Name is required ";
} else {
$fname = $_POST["fname"];
}
// LAST NAME
if (empty($_POST["lname"])) {
$errorMSG = "Last Name is required ";
} else {
$lname = $_POST["lname"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// PHONE
if (empty($_POST["phone"])) {
$errorMSG .= "Phone Number is required ";
} else {
$phone = $_POST["phone"];
}
// SERVICE
if (empty($_POST["service"])) {
$errorMSG .= "Service Choice is required ";
} else {
$service = $_POST["service"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "myemail#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body .= "First Name: ";
$Body .= $fname;
$Body .= "\n";
$Body .= "Last Name: ";
$Body .= $lname;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Service: ";
$Body .= $service;
$Body .= "\n";
$Body .= "Message ";
$Body .= "\n";
$Body .= $message;
// 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;
}
}
?>
JAVASCRIPT
$("#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 fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var phone = $("#phone").val();
var service = $("#service").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "fname=" + fname + "&lname=" + lname + "&phone=" + phone + "&email=" + email + "&service=" + service + "&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);
}
Anyone who can help with this would be great, its the last piece of the website I need to get done.
Thanks a bunch!
As output is coming as "Something went wrong :(" so as per your code i.e
$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;
}
}
the mail is not been sent and you are getting false in $success i.e while sending mail. Also the else condition can be improve:
if(!empty($errorMSG)){
echo "Something went wrong, error: " . $errorMSG;
} else {
echo "Mail not sent";
}

Submit Contact Form w/o Reloading Page Using Ajax

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')

Invalid email upon contact form send

I get an "invalid email" upon sending, even though the email is correct. I am having doubts about this code. Could someone take a glance?
Here's the HTML
<form id="contact-form" action="email.php" method="post" class="clearfix">
<div class="contact-box-hide">
<div class="col-sm-6">
<input type="text" class="form-control" id="first_name" name="first_name" required placeholder="Navn">
<span class="first-name-error"></span>
</div>
<div class="col-sm-6">
<input type="text" class="form-control" id="last_name" name="last_name" required placeholder="Efternavn">
<span class="last-name-error"></span>
</div>
<div class="col-sm-6">
<input type="email" class="form-control" id="email" name="contact_email" required placeholder="Email">
<span class="contact-email-error"></span>
</div>
<div class="col-sm-6">
<input type="text" class="form-control" id="subject" name="contact_subject" required placeholder="Hvor skal oplægget afholdes?">
<span class="contact-subject-error"></span>
</div>
<!--<div class="col-sm-6">
<label class=".radio-inline">
<input type="radio" class="form-control" id="choice" name="options" required placeholder="Emne">
<span class="contact-subject-error"></span>Option 1
</label>
<label class=".radio-inline" style="border-left: 0px;" >
<input type="radio" class="form-control" id="choice" name="options" required placeholder="Emne">
<span class="contact-subject-error"></span>Option 2
</label>
</div>
-->
<!--<div class="col-sm-20">
<input type="radio" class="form-control" id="contact_type" name="nummer 1" checked>
<span class="contact-x-error"></span>
</div>
<div class="col-sm-20">
<input type="radio" class="form-control" id="contact_type" name="nummer 1" checked>
<span class="contact-x-error"></span>
</div>
-->
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="message" name="message" required placeholder="Besked"></textarea>
<span class="contact-message-error"></span>
</div>
<div class="col-sm-2">
<button id="contact-submit" class="btn custom-btn col-xs-12" type="submit" name="submit"><i class="fa fa-angle-right"></i></button>
<span id="contact-loading" class="btn custom-btn col-xs-12"> <i class="fa fa-refresh fa-spin"></i> </span>
</div>
</div><!-- /.contact-box-hide -->
<div class="contact-message"></div>
</form>
Here's the email.php (the contact.php, which the .js is calling, is identical):
<?php
if($_REQUEST['first_name'] == '' || $_REQUEST['contact_email'] == '' || $_REQUEST['message'] == ''):
return "error";
endif;
if (filter_var($_REQUEST['contact_email'], FILTER_VALIDATE_EMAIL)):
$subject = 'Fra Kriger til Kaemper - kontaktformular'; // Subject of your email
// Receiver email address
$to = 'geerrift#gmail.com'; //Change the email address by yours
// prepare header
$header = 'From: '. $_REQUEST['first_name'] . " " .$_REQUEST['last_name'] . ' <'. $_REQUEST['contact_email'] .'>'. "\r\n";
$header .= 'Reply-To: '. $_REQUEST['first_name'] . " " .$_REQUEST['last_name'] . ' <'. $_REQUEST['contact_email'] .'>'. "\r\n";
// $header .= 'Cc: ' . 'example#domain.com' . "\r\n";
// $header .= 'Bcc: ' . 'example#domain.com' . "\r\n";
$header .= 'X-Mailer: PHP/' . phpversion();
$message .= 'Name: ' . $_REQUEST['first_name'] . " " .$_REQUEST['last_name'] . "\n";
$message .= 'Email: ' . $_REQUEST['contact_email'] . "\n";
$message .= 'Subject: ' . $_REQUEST['contact_subject'] . "\n";
$message .= 'Message: '. $_REQUEST['message'];
// Send contact information
$mail = mail( $to, $subject , $message, $header );
echo 'sent';
else:
return "error";
endif;
?>
Here is the .js:
$('#contact-submit').click(function () {
$('.first-name-error, .last-name-error, .contact-email-error, .contact-subject-error, .contact-message-error').hide();
var first_nameVal = $('input[name=first_name]').val();
var last_nameVal = $('input[name=last_name]').val();
var emailReg = /^(([^<>()[\]\\.,;:\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,}))$/igm;
var emailVal = $('#contact_email').val();
var contact_subjectVal = $('input[name=contact_subject]').val();
var messageVal = $('textarea[name=message]').val();
//validate
if (first_nameVal == '' || first_nameVal == 'First Name *') {
$('.first-name-error').html('<i class="fa fa-exclamation"></i> Vi har brug for dit fornavn.').fadeIn();
return false;
}
if (last_nameVal == '' || last_nameVal == 'Last Name *') {
$('.last-name-error').html('<i class="fa fa-exclamation"></i> Vi har brug for dit efternavn.').fadeIn();
return false;
}
if (emailVal == "" || emailVal == "Email Address *") {
$('.contact-email-error').html('<i class="fa fa-exclamation"></i> Vi har brug for din mailadresse.').fadeIn();
return false;
} else if (!emailReg.test(emailVal)) {
$('.contact-email-error').html('<i class="fa fa-exclamation"></i> Ugyldig mailadresse.').fadeIn();
return false;
}
if (contact_subjectVal == '' || contact_subjectVal == 'Subject *') {
$('.contact-subject-error').html('<i class="fa fa-exclamation"></i> Subject is required.').fadeIn();
return false;
}
if (messageVal == '' || messageVal == 'Message *') {
$('.contact-message-error').html('<i class="fa fa-exclamation"></i> Skriv venligst en henvendelse.').fadeIn();
return false;
}
var data_string = $('.contact-form').serialize();
$('#contact-submit').hide();
$('#contact-loading').fadeIn();
$('.contact-error-field').fadeOut();
$.ajax({
type: "POST",
url: "php/contact.php",
data: data_string,
//success
success: function (data) {
$('.contact-box-hide').slideUp();
$('.contact-message').html('<i class="fa fa-check contact-success"></i><div>Your message has been sent.</div>').fadeIn();
},
error: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-exclamation contact-error"></i><div>Something went wrong, please try again later.</div>').fadeIn();
}
}) //end ajax call
return false;
});
Please tell me if I've left anything out, and I'll provide it immediately!
Change
var emailVal = $('#contact_email').val();
to
var emailVal = $('#email').val();
or
var emailVal = $('input[name="contact_email"]').val();
On your email field you have an ID of email and a NAME of contact_email. When using the hash (#) in jQuery you're searching for the ID, not the name. So your script wan't able to find the email value.

Categories