Modal window closes on submit - javascript

I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});

I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});

I think you forget to put exit(); at the end of file contact-form.php

Related

Wordpress PHP Contact form - problem with displaying message about sent mail

I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>

Contact form doesn't send textarea value [duplicate]

When i send an email with my contact form the textarea value does not send and the "message:" field is always empty in the email.
Declaring the input variables manually in jquery instead of using serialize gives the same result.
The textarea is inside the form tags so i have no idea why its value is not picked up and posted.
I've tried giving the textarea an id="message" and calling it manually in jquery like: var text = $("#message").val(); and var text = $("textarea#message").val(); but it still doesn't send.
I don't know what i'm doing wrong. Please help.
Here is my code:
<form id="contactForm" method="POST">
<div class="row small-margin">
<div class="col-md-4">
<i class="pe-7s-user pe-2x icon-contact"></i>
<input name="name" type="text" placeholder="Name(required)" required size="35">
</div>
<div class="col-md-4">
<i class="pe-7s-mail pe-2x icon-contact"></i>
<input name="email" type="email" placeholder="Email(required)" required size="35">
</div>
<div class="col-md-4">
<i class="pe-7s-link pe-2x icon-contact"></i>
<input name="website" type="text" placeholder="Website" size="35">
</div>
</div>
<div class="row small-margin">
<div class="col-md-12">
<!-- Message Field -->
<textarea name="message" placeholder="Your Message(required)" required></textarea>
<!-- Submit Button -->
<button id="submit" name="submit" type="submit" class="button" value="submit">SEND MESSAGE</button>
<!-- Success Message -->
<div id="msgSubmit" class="alert alert-success text-center hidden">Message Sent Successfully</div>
</div>
</div>
</form>
And JS:
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
console.log( $( this ).serialize() );
});
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&website=" + website + "&message=" + text,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
And PHP:
<?php
// Set variables
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$message = $_POST['text'];
$to = 'novakim92#gmail.com';
$subject = 'New Message from Nixo';
// Prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Website: ";
$Body .= $website;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// Send email
$success = mail($to, $subject, $Body, "From:".$email);
if ($success){
echo "success";
}else{
echo "<p>Something went wrong, please try again!</p>";
}
?>
I found the issue on your code:
the Values from textarea never made it the Server side, because you are doing this in your PHP:
$message = $_POST['text'];
You should do this in order to get the value from textarea:
$message = $_POST['message'];
This will solve your issue :). Hope it helps.
Your variable naming is inconsistent.
In your HTML-form you're using message for the name-attribute.
But in you're AJAX-call and in the PHP $_POST-GLOBAL you are looking for a variable called text.

Contact form sends mail with empty message field

When i send an email with my contact form the textarea value does not send and the "message:" field is always empty in the email.
Declaring the input variables manually in jquery instead of using serialize gives the same result.
The textarea is inside the form tags so i have no idea why its value is not picked up and posted.
I've tried giving the textarea an id="message" and calling it manually in jquery like: var text = $("#message").val(); and var text = $("textarea#message").val(); but it still doesn't send.
I don't know what i'm doing wrong. Please help.
Here is my code:
<form id="contactForm" method="POST">
<div class="row small-margin">
<div class="col-md-4">
<i class="pe-7s-user pe-2x icon-contact"></i>
<input name="name" type="text" placeholder="Name(required)" required size="35">
</div>
<div class="col-md-4">
<i class="pe-7s-mail pe-2x icon-contact"></i>
<input name="email" type="email" placeholder="Email(required)" required size="35">
</div>
<div class="col-md-4">
<i class="pe-7s-link pe-2x icon-contact"></i>
<input name="website" type="text" placeholder="Website" size="35">
</div>
</div>
<div class="row small-margin">
<div class="col-md-12">
<!-- Message Field -->
<textarea name="message" placeholder="Your Message(required)" required></textarea>
<!-- Submit Button -->
<button id="submit" name="submit" type="submit" class="button" value="submit">SEND MESSAGE</button>
<!-- Success Message -->
<div id="msgSubmit" class="alert alert-success text-center hidden">Message Sent Successfully</div>
</div>
</div>
</form>
And JS:
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
console.log( $( this ).serialize() );
});
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&website=" + website + "&message=" + text,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
And PHP:
<?php
// Set variables
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$message = $_POST['text'];
$to = 'novakim92#gmail.com';
$subject = 'New Message from Nixo';
// Prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Website: ";
$Body .= $website;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// Send email
$success = mail($to, $subject, $Body, "From:".$email);
if ($success){
echo "success";
}else{
echo "<p>Something went wrong, please try again!</p>";
}
?>
I found the issue on your code:
the Values from textarea never made it the Server side, because you are doing this in your PHP:
$message = $_POST['text'];
You should do this in order to get the value from textarea:
$message = $_POST['message'];
This will solve your issue :). Hope it helps.
Your variable naming is inconsistent.
In your HTML-form you're using message for the name-attribute.
But in you're AJAX-call and in the PHP $_POST-GLOBAL you are looking for a variable called text.

Bootstrap Contact Form with PHP, jQuery and AJAX

Hi having a problem with my contact form submission ,Its a Bootstrap template, its got JQuery validation, but there wasn't any PHP file for contact, i tried many different code for contact.php but it doesn't work,
some of them showing "message sent successfully" but i didn't receive any email. i am using "Google Apps For Work" as my email client only. please help, really appreciate.
(Sorry about my poor English.)
Here the code for index.php`
<form action="Contact.php" method="post" id="sky-form3" class="sky-form contact-style">
<fieldset>
<label>Name</label>
<div class="row">
<div class="col-md-7 margin-bottom-20 col-md-offset-0">
<div>
<input type="text" name="name" id="name" class="form-control">
</div>
</div>
</div>
<label>Email <span class="color-red">*</span></label>
<div class="row">
<div class="col-md-7 margin-bottom-20 col-md-offset-0">
<div>
<input type="text" name="email" id="email" class="form-control">
</div>
</div>
</div>
<label>Message</label>
<div class="row">
<div class="col-md-11 margin-bottom-20 col-md-offset-0">
<div>
<textarea rows="8" name="message" id="message" class="form-control"></textarea>
</div>
</div>
</div>
<p><button type="submit" class="btn-u btn-brd btn-brd-hover btn-u-dark">Send Message</button>
<button type="reset" class="btn-u btn-brd btn-brd-hover btn-u-dark">Reset Messages</button></p>
</fieldset>
<div class="message">
<i class="rounded-x fa fa-check"></i>
<p>Your message was successfully sent!</p>
</div>
</form>
Here the code for my contact.php file
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
<?php
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'contact#vertigosourcing.com';
$name = addslashes(trim($_POST['name']));
$Email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
$array = array('nameMessage' => '', 'emailMessage' => '', 'messageMessage' => '');
if(!isEmail($Email)) {
$array['emailMessage'] = 'Invalid email!';
}
if($subject == '') {
$array['nameMessage'] = 'Empty name!';
}
if($message == '') {
$array['messageMessage'] = 'Empty message!';
}
if(isEmail($Email) && $name != '' && $message != '') {
// Send email
$headers = "From: " . $Email . " <" . $Email . ">" . "\r\n" . "Reply-To: " . $Email;
mail($emailTo, $subject . " (contact request from)", $message, $headers);
}
}
?>
If you are using xampp/lamp/wamp, it won't work that easy, you have to activate some functions to send an email from a localhost, I think that's the problem because you have no mistakes in your code.
You can also try using #mail() instead of mail().

I cannot get my webform to send (php, 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

Categories