HTML PHP Form does not send data to Email [duplicate] - php

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
As an mildly-intermediate web developer, I have never actually implemented a contact form until now. The problem is that I can't get the email to actually go through.
HTML:
<form action="php/handleFormSubmit.php" id="contact-form" role="form" method="POST">
<div class="ajax-hidden">
<div class="form-group wow fadeInUp">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Name">
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".1s">
<label class="sr-only" for="c_email">Email</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".2s">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-block wow fadeInUp" data-wow-delay=".3s">Send Message</button>
</div>
<div class="ajax-response"></div>
</form>
PHP:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['c_name'];
$visitor_email = $_POST['c_email'];
$message = $_POST['c_message'];
$email_from = "email#email.com";
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message".
$to = "email#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to,$email_subject,$email_body,$headers);
}
if(isset($_POST['c_name'])){
$res['sendstatus'] = 1;
$res['message'] = 'Form Submission Successful';
echo json_encode($res);
}
?>
I know the if(isset($_POST['submit'])) gets rid of the annoying email when refreshing/landing but my submit does not go to my email.
Help? I appreciate it.

Check the first line,
it says if $_POST['submit'] is set then do this{}.
but your html form doesn't have that field.
ADD this field in your form:
<input type="hidden" name="submit">

Code for sending Mails via Ajax
<?php
if($_POST)
{
$to_email = "er.shakun90#gmail.com"; //Recipient email, Replace with own email here
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
//$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
//$country_code = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT);
$phone_number = filter_var($_POST["user_phone"], FILTER_SANITIZE_NUMBER_INT);
//$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_name)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$user_email = 'contact#sanktik.net';
//email body
$message_body = $message."\r\n\r\n-".$user_name."\r\nPhone Number :". $phone_number ;
$sunject = "New enquiry from wesbite";
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your interest.Our Team Member will get in touch with you shortly'));
die($output);
}
}
?>

Change your button code to:
<button type="submit" name="Submit" class="btn btn-lg btn-block wow fadeInUp" data-wow-delay=".3s">Send Message</button>
and your php file first line to:
if(isset($_POST['Submit']))

Don't check if the button exists in the POST array. It makes sense if you click the button or submit the form via Enter press! I think by submitting via Enter press, the submit button doesn't exist!
Solution below is insensitive:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// sent
Important things:
Check if form is real posted (see above)
Validate your input
Sanatize your input
After that, you can do your actions, e.g. mail or saving to database.

Related

PHP Form Not Showing Full Information on Submission

I have a very simple form from a template with just three fields - Name - Email - Phone. When submitted the form works. BUT - if in the name field you have two words, e.g, John Smith - then it still submits but then everything after the first word gets truncated - so for the example, the mail received would show only "john" and not show "smith", neither will it show email or phone values. I have given my code samples below.. any help is highly appreciated.
PHP CODE BELOW
<?php
$to = 'x#gmail.com, y#gmail.com' ; // Put in your email address here
$subject = "Appointment Request"; // The default subject. Will appear by default in all messages. Change this if you want.
// User info (DO NOT EDIT!)
$name = stripslashes($_REQUEST['name']); // sender's name
$email = stripslashes($_REQUEST['email']); // sender's email
$phone = stripslashes($_REQUEST['phone']);
// The message you will receive in your mailbox
// Each parts are commented to help you understand what it does exaclty.
// YOU DON'T NEED TO EDIT IT BELOW BUT IF YOU DO, DO IT WITH CAUTION!
$msg = "Name: ".$name."\r\n"; // add sender's name to the message
$msg .= "E-mail: ".$email."\r\n"; // add sender's email to the message
$msg .= "Phone: ".$phone."\r\n"; // add sender's email to the message
$msg .= "Subject: ".$subject."\r\n\n"; // add subject to the message (optional! It will be displayed in the header anyway)
$msg .= "---Message--- \r\n";
$msg .= "\r\n\n";
$mail = #mail($to, $subject, $msg, "From:".$email); // This command sends the e-mail to the e-mail address contained in the $to variable
if($mail) {
echo 'Your message has been sent, we will be in touch shortly!'; //This is the message that will be shown when the message is successfully send
} else {
echo 'Message could not be sent!'; //This is the message that will be shown when an error occured: the message was not send
}
?>
HTML FORM CODE
<form role="form" onSubmit="return send_email();">
<div class="form-group">
<label for="exampleInputName">Name</label>
<input type="text" class="form-control" id="app_name" placeholder="Name" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">E-mail</label>
<input type="text" class="form-control" id="app_email" placeholder="E-mail" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="text" class="form-control" id="app_phone" placeholder="Phone">
</div>
<button type="submit" class="btn btn-block btn-orange btn-Submit" onclick="ga('send', 'event', 'formsubmit', 'lp form', 'LP form');">Book my Free Consultation</button>
<small id="mail_msg"></small>
</form>
send_email() is actually in a JS file in a separate JS folder.. I have pasted the code below..
JS send_email
function send_email() {
var name=$("#app_name").val();
var email=$("#app_email").val();
var phone=$("#app_phone").val();
if(name=="")
{
$("#app_name").addClass("errors");
}
else
{
$("#app_name").removeClass("errors");
}
if(!validEmail(email))
{
$("#app_email").addClass("errors");
}
else
{
$("#app_email").removeClass("errors");
}
if(phone=="")
{
$("#app_phone").addClass("errors");
}
else
{
$("#app_phone").removeClass("errors");
}
if(name!="" && phone!="" && validEmail(email) )
{
$("#mail_msg").load("email.php?name="+name+"&email="+email+"&phone="+phone);
$("#app_name").val('');
$("#app_email").val('');
$("#app_phone").val('');
}
return false;
}
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}

Getting error when the contact form be submitted

Getting error when the contact form should be submitted.
Undefined index: HTTP_X_REQUESTED_WITH in C:\xampp\htdocs\dishadwellings\dishaparkwest\contact.php on line 7
{"type":"error","text":"Sorry Request must be Ajax POST"}
Here is the HTML FORM code:
<form action="contact.php" method="POST">
<input type="text" name="do-input-name" id="do-input-name" placeholder="Name">
<input type="email" name="do-input-email" id="do-input-email" placeholder="Email">
<input type="text" name="do-input-web" id="do-input-web" placeholder="Web">
<textarea name="do-input-message" id="do-input-message" cols="30" rows="10" class="do-input-message" placeholder="Comment"></textarea>
<button type="submit" id="do-submit-btn" class="do-btn-round-solid">SEND</button>
</form>
Here is the code for the contact form: I could not rectify the error. Kindly do the favour to solve this issue
<?php
if($_POST)
{
$to_email = "abc#gmail.com"; //Recipient email, Replace with own email here
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($name)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email;
//proceed with PHP email.
$headers = 'From: '.$name.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
die($output);
}
}
?>
Try your if condition as follow:
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
The next thing is, you are submitting form via normal HTML form and you are trying to check that submit data OR send email only if its ajax submit. which is not truth and so it not works.
To make your code working, either submit your form data via ajax OR remove this if condition shown above.
Your post code
<?php
if($_POST)
{
$to_email = "abc#gmail.com"; //Recipient email, Replace with own email here
//Sanitize input data using PHP filter_var().
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$subject = "Test email";
$user_name = "Sharnya";
//additional php validation
if(strlen($name)<4){ // If length is less than 4 it will output JSON error.
$output = 'Name is too short or empty!';
die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = 'Please enter a valid email!';
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = 'Too short message! Please enter something.';
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email;
//proceed with PHP email.
$headers = 'From: '.$name.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = 'Could not send mail! Please check your PHP mail configuration.';
die($output);
}else{
$output = 'Hi '.$user_name .' Thank you for your email';
die($output);
}
}
?>
HTML form code:
<form action="contact.php" method="POST" enctype="text/plain">
<input type="text" name="name" id="name" placeholder="Name">
<input type="email" name="email" id="email" placeholder="Email">
<input type="text" name="web" id="web" placeholder="Web">
<textarea name="message" id="message" cols="30" rows="10" class="message" placeholder="Comment"></textarea>
<button type="submit" id="submit" class="do-btn-round-solid">SEND</button>
</form>
Happy coding!

PHP email contact form displays error

Every time I attempt to submit this contact form I receive the following error message:
'Please enter your message.'
The name error message and email error message do not appear unless I leave them blank. I attempted specifying post in the HTML.
Here is the HTML:
<div class="col-md-8 animated fadeInLeft notransition">
<h1 class="smalltitle">
<span>Get in Touch</span>
</h1>
<form action="contact.php" method="post" name="MYFORM" id="MYFORM">
<input name="name" size="30" type="text" id="name" class="col-md-6 leftradius" placeholder="Your Name">
<input name="email" size="30" type="text" id="email" class="col-md-6 rightradius" placeholder="E-mail Address">
<textarea id="message" name="message" class="col-md-12 allradius" placeholder="Message" rows="9"></textarea>
<img src="contact/refresh.jpg" width="25" alt="" id="refresh"/><img src="contact/get_captcha.php" alt="" id="captcha"/>
<br/><input name="code" type="text" id="code" placeholder="Enter Captcha" class="top10">
<br/>
<input value="Send" type="submit" id="Send" class="btn btn-default btn-md">
</form>
</div>
Here is the PHP:
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'faasdfsdfs#gmail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
In your HTML form you name your <input... field "message" but then when you are in PHP you try to get the value from `$_GET['comment'].
I think if you get those lined up I think it will solve your problem.
I can see 2 issues:
Receive $_GET['comment'] or $_POST['comment'] but next you're using $message var
Do not use if($_POST) because $_POST as a superglobal
is always setted.
I suggest use this for check if a POST have been sent
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {}
or this in case you want to check is not empty
if ( !empty($_POST) ) {}
How to detect if $_POST is set?

reCAPTCHA and PHP to send an Email Form

I'm using GoDaddy as my web server.
I'm trying to implement reCAPTCHA into my email form for my website, however it seems to not be able to work. That is, I pass the reCAPTCHA test but the email isn't sent.
I've only used PHP and HTML for the site so far.
I have also added the script to my head tag
<script src='https://www.google.com/recaptcha/api.js'></script>
Here are the code snippets.
HTML:
<form action="#" id="form" method="post" name="form">
<div class="form-group">
<label for="name-field">Name</label>
<input name="vname" class="form-control" placeholder="Enter Your Full Name" type="text" value="">
</div>
<div class="form-group">
<label for="email-field">Email address</label>
<input name="vemail" class="form-control" placeholder="Enter Your Email" type="text" value="">
</div>
<div class="form-group">
<label for="contract-field">Enter Contract Here</label>
<textarea name="msg" class="form-control" placeholder="Enter Contract Here" rows="5"></textarea>
</div>
<div class="g-recaptcha form-group" data-sitekey="SITEKEY"></div>
<div class="form-group"><button id="send" name="submit" type="submit" class="btn btn-default">Submit</button></div>
</form>
PHP:
<?php
//Checking For reCAPTCHA
$captcha;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
// Checking For correct reCAPTCHA
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SECRETKEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false){
echo "Your CAPTCHA response was wrong."
exit;
}
else{
// Checking For Blank Fields..
if($_POST["vname"]==""||$_POST["vemail"]==""||$_POST["msg"]==""){
echo "Fill All Fields..";
}
else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['vemail'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$to = 'johdoe#example.com';
$subject = 'Test';
$message = $_POST['msg'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70, "\r\n");
// Send Mail By PHP Mail Function
mail($to, $subject, $message, $headers);
echo "Your mail has been sent successfully!";
}
}
} else {
echo "Your CAPTCHA response was wrong. Try again."
exit;
}?>
Am I implementing server-side wrong? Or is it client side?
Your code has syntax errors in if and else. Just rewrite your code as given below and try it.
<?php
//Checking For reCAPTCHA
$captcha;
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
}
// Checking For correct reCAPTCHA
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SECRETKEY&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
if (!$captcha || $response.success == false) {
echo "Your CAPTCHA response was wrong.";
exit ;
} else {
// Checking For Blank Fields..
if ($_POST["vname"] == "" || $_POST["vemail"] == "" || $_POST["msg"] == "") {
echo "Fill All Fields..";
} else {
// Check if the "Sender's Email" input field is filled out
$email = $_POST['vemail'];
// Sanitize E-mail Address
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
echo "Invalid Sender's Email";
} else {
$to = 'johdoe#example.com';
$subject = 'Test';
$message = $_POST['msg'];
$headers = 'From:' . $email . "\r\n";
// Sender's Email
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70, "\r\n");
// Send Mail By PHP Mail Function
if (mail($to, $subject, $message, $headers)) {
echo "Your mail has been sent successfully!";
} else {
echo "Failed to send email, try again.";
exit ;
}
}
}
}
?>

My contact form is working but it won't show the success message

My contact form is working but the success message doesn't show. Another developer wrote the PHP code but I did some of the jQuery and it won't display my message. I'm pretty sure the problem is with the jQuery. I'm particularly confused by this line of code...
$("#result").hide().html(output).slideDown();
}, 'json');
}
I would think you would want to use .show() since #result is needed to show the html but that didn't seem to do the trick. The full code is below.
$(function(){
$(".btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val(),
user_email = $('input[name=email]').val(),
user_message = $('textarea[name=message]').val(),
proceed = true;
//simple validation at client's end
//we simply change border color to red if empty field using .css()
if(user_name===""){
$('input[name=name]').css('border','2px solid red').after('<p class="error-msg">(What\'s your name?)</p>');
proceed = false;
}
if(user_email===""){
$('input[name=email]').css('border','2px solid red').after('<p class="error-msg">(Please provide a valid email)</p>');
proceed = false;
}
if(user_message==="") {
$('textarea[name=message]').css('border','2px solid red').after('<p class="error-msg">(Please let me know what your inquiry is about)</p>');
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
//Ajax post data to server
$.post('../../contact-form.php', post_data, function(response){
//load json data from server and output message
if(response.type === 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
alert('Thanks for the message');
//reset values in all input fields
$('.form-container input').val('');
$('.form-container textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$(".form-container input, .form-container textarea").keyup(function() {
$(".form-container input, .form-container textarea").css('border-color','');
$("#result").slideUp();
});
});
PHP code
<?php
if($_POST)
{
$to_Email = "alexechaparro#gmail.com"; //Replace with recipient email address
$subject = 'alexsdogvacay.com'; //Subject line for emails
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
var_dump($_REQUEST);
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
echo $_POST["userName"];
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
/*
Incase your host only allows emails from local domain,
you should un-comment the first line below, and remove the second header line.
Of-course you need to enter your own email address here, which exists in your cp.
*/
//$headers = 'From: your-name#YOUR-DOMAIN.COM' . "\r\n" .
$headers = 'From: '.$user_Email.'' . "\r\n" . //remove this line if line above this is un-commented
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// send mail
$sentMail = #mail($to_Email, $subject, $user_Message .' -'.$user_Name, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email. I will get back to you as soon as possible.'));
die($output);
}
}
?>
So, the line of code that's confusing: $('#result').hide().html().slideDown(); works. No need for changing that. One problem I see is that your variable output isn't being defined with var making it a global variable.
That aside, the php code seems to kill the success response with the die function, bc it doesn't return anything to the output. change this:
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email. I will get back to you as soon as possible.'));
die($output);
}
TO:
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your email. I will get back to you as soon as possible.'));
}
echo $output;
Hope this helps!
T
This is the second time I got burnt because of my HTML. Previously my HTML was...
<form id="contact_form">
<div id="result"></div>
<div class="form-group">
<label for="name" id="name">Name</label>
<input type="text" name="name" class="form-control" id="exampleInputName" placeholder="Name" required>
</div>
<div class="form-group">
<label for="Email" id="email">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Email" required>
</div>
<div class="form-group">
<label for="Message" id="message">Message</label>
<textarea rows="4" name='message'class="form-control" placeholder="Message" required></textarea>
</div>
<div><span> </span>
<input type="button" class="btn btn-default" id='submit_btn' value="Submit">
</div>
</form>
All I did was change my form to a fieldset and my input to
<button class="btn btn-default" id="submit_btn">Submit</button>
I'm honestly not sure why that fixed it, but it did.

Categories