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;
}
Related
I'm having an issue with my website. To give some context, I've worked on it using ReactJS for the front-end and Express for the back-end. BUT, my hosting provider doesn't support Node, so I had to change the back-end part to PHP. I only developed the contact form functionality.
I'm not sure if I'm missing something, but I would like to ask your opinion to continue due to I'm stuck.
Here's the front-end part for Contact.js:
import React, {Component} from 'react';
class Contact extends Component{
render(){
return(
<div>
<form id="contact-form" name="c-form" method="post" action="/mailer.php">
<div className="input-field">
<input
id="first_name"
type="text"
className="validate"
name="first_name"
required/>
<label for="first_name">Name</label>
</div>
<div className="input-field">
<input id="sub" type="text" className="validate" name="sub"/>
<label for="sub">Subject</label>
</div>
<div className="input-field">
<input id="email" type="email" className="validate" name="email" required/>
<label for="email">Email</label>
</div>
<div className="input-field">
<textarea
id="textarea1"
className="materialize-textarea"
name="message"
required></textarea>
<label for="textarea1">Message</label>
</div>
<div className="contact-send">
<button
id="submit"
name="contactSubmit"
type="submit"
value="Submit"
className="btn waves-effect">Send
</button>
</div>
</form>
</div>
)
}
}
export default Contact;
and also, the back-end part in the PHP file, mailer.php located under /src folder:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "*HERE I PLACED MY EMAIL*";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
The result is:
POST http://www.*mywebsite.com*/mailer.php 400 (Bad Request)
Any suggestion or recommendation? Thanks in advance!
change mailer.php
$name = strip_tags(trim($_POST["name"]));
to
$name = strip_tags(trim($_POST["first_name"]));
I'm using a simple html contact form to submit contact details to a php file using Ajax / jQuery (v 1.10.2). The php sends an email and returns an error or "OK" on success. However I'm getting a "No Transport" error when I click the Submit button and the form isn't submitting.
I have a html form element with an id and I'm using "$('#contactForm').submit" in jQuery to submit the form. The strange thing is that it worked maybe 3 or 4 times in the past few days, so it works at random now and again. I tried not using jQuery and adding an action method directly to the form element (form action="inc/sendEmail.php" method="post") and this works, however the web page then redirects to the php file but I want to stay on the html page and not redirect.
- I searched for ajax and "no transport" error and most of the replies mention CORS, but my js is just calling a php script on the same server so it can't be anything to do with CORS (can it?)
- This was working a few months ago but I recently added SSL to the domain, but again I can't see how this can make a difference as the html, js, and php are all on the same server.
<form id="contactForm">
<div class="col-md-6">
<div class="form-group">
<label for="InputName">Your Name</label>
<div class="input-group">
<input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span>
</div>
</div>
<div class="form-group">
<label for="InputEmail">Your Email</label>
<div class="input-group">
<input type="email" class="form-control" id="InputEmail" name="InputEmail" placeholder="Enter Email" required >
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span>
</div>
</div>
<div class="form-group">
<label for="InputMessage">Message</label>
<div class="input-group">
<textarea name="InputMessage" id="InputMessage" class="form-control" placeholder="Enter Email" rows="5" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span>
</div>
</div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</form>
$('#contactForm').submit(function(e) {
e.preventDefault();
var contactName = $('#contactForm #InputName').val();
var contactEmail = $('#contactForm #InputEmail').val();
var contactSubject = '';
var contactMessage = $('#contactForm #InputMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
async: false,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#message-warning').html(msg);
}
},
error: function (xhr, desc, err)
{
// GETTING "No Transport" ERROR HERE
$('#message-warning').html('Error message: ' + err);
$('#message-warning').fadeIn();
}
});
return false;
});
<?php
$siteOwnersEmail = 'abc#xyz.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact form submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
I expect the form to be submitted to the php script when the input fields are valid, then the contact form should be hidden if an OK message comes back from the php. However I'm getting a "No Transport" error when I click submit and the form isn't being submitted at all (there's no entry in the "Network" panel in browser dev tools).
Ok I think I figured it out. It looks like there was an issue with ajax submitting to the php file over SSL - even though the path to the php file is relative and the site is already on https. I read that an older version of the jquery library may have this issue so I upgraded to a higher version (1.10.2 to 1.11.3) which seems to have fixed the issue. More testing required but it looks good so far.
So I need to implement an AJAX information submit form. I'm using this example built by the guys at Treehouse… http://blog.teamtreehouse.com/create-ajax-contact-form
First part of the question… How do I add new fields? I've tried editing the .php .js and .html, getting them all in line to what I believe is right but upon testing my solution fails.
The fields I require…
Name:
Location:
Post Code:
Date of Birth:
URL Link:
Message (200 words):
The second part… Can I run two of these on the same page?
Cheers in advance for any help! - you can email me garethyo#gmail.com if you want me to send code etc.
CODE BELOW —
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="link">Link:</label>
<input type="text" id="link" name="link" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
JS
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#link').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
PHP
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "garethyo#gmail.com";
// Set the email subject.
$subject = "A Future Bubbler… $name ";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Link: $link\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
You never define $link. You need to add $link = trim($_POST['link']); before $message = trim($_POST["message"]);. – Sean Apr 4 at 20:50
— Sean, CEO Worldstar
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 ;
}
}
}
}
?>
I am creating a website and I was making a contact form with PHP. It is turning up no errors on the page itself but the email never shows up in the inbox or spam folder of my email. The code I have for it is:
$_NAME = $_POST["name"];
$_EMAIL = $_POST["reply"];
$_SUBJECT = $_POST["subject"];
$_MESSAGE = $_POST["message"];
$_MAILTO = "myemail#gmail.com";
$_SUBJECT = "Contact Form";
$_FORMCONTENT = "From: ".$_NAME." Subject: ".$_SUBJECT." Message: ".$_MESSAGE;
$_MAILHEADER = "Reply To: ".$_EMAIL;
mail($_MAILTO, $_SUBJECT, $_FORMCONTENT, $_MAILHEADER);
Any ideas what the problem is?
EDIT --
Here's the HTML form:
<form id="contact" name="contact" action="contact2.php" method="post">
<input type="text" class="name" name="name" id="name" placeholder="Your name (optional)" onfocus="placeholder=''" onblur="placeholder='Your name (optional)'" /><br><br>
<input type="text" class="reply" id="reply" name="reply" placeholder="Your email (optional)" onfocus="placeholder=''" onblur="placeholder='Your email (optional)'" /><br><br>
<input type="text" class="subject" id="subject" name="subject" placeholder="Subject" onfocus="placeholder=''" onblur="placeholder='Subject'" /><br><br>
<textarea class="message" id="message" name="message" rows="10" cols="50" placeholder="Enter your message" onfocus="placeholder=''" onblur="placeholder='Enter your message'"></textarea><br><br>
<input type="submit" class="send" id="send" name="send" value="Send Message" />
</form>
First step would be to check the return value of the mail function to see if the email was successfully (as far as PHP/mail function can ascertain) sent.
$mail_result = mail($_MAILTO, $_SUBJECT, $_FORMCONTENT, $_MAILHEADER);
if ($mail_result) {
echo <<<HTML
<div>Mail was successfully sent!</div>
HTML;
} else {
echo <<<HTML
<div>Sending mail failed!</div>
HTML;
}
Secondly, you should check that all appropriate settings are correctly set in your php.ini file, specifically the sendmail_path setting. You should definitely take a look at official documentation in the PHP Manual.
As a last ditch effort, you may want to look into an alternate method of sending the mail.
Simple Example:
<?php
// Has the form been submitted?
if (isset($_POST['send'])) {
// Set some variables
$required_fields = array('name', 'email'); // add fields as needed
$errors = array();
$success_message = "Congrats! Your message has been sent successfully!";
$sendmail_error_message = "Oops! Something has gone wrong, please try later.";
// Cool the form has been submitted! Let's loop
// through the required fields and check
// if they meet our condition(s)
foreach ($required_fields as $fieldName) {
// If the current field in the loop is NOT part of the form submission -OR-
// if the current field in the loop is empty
if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
// add a reference to the errors array, indicating that these conditions have failed
$errors[$fieldName] = "The {$fieldName} is required!";
}
}
// Proceed if there aren't any errors
if (empty($errors)) {
// add fields as needed
$name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
$email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
// Email receivers
$to_emails = "anonymous1#example.com, anonymous2#example.com";
$subject = 'Contact form sent from ' . $name;
$message = "From: {$name}";
$message .= "Email: {$email}";
$headers = "From: {$name}\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if (mail($to_emails, $subject, $message, $headers)) {
echo $success_message;
} else {
echo $sendmail_error_message;
}
} else {
foreach($errors as $invalid_field_msg) {
echo "<p>{$invalid_field_msg}</p>";
}
}
}