I should solve a problem with a contact form and I don't know where to put my hands anymore.
I have a form in HTML, then a validation in JS and finally an email sending in PHP.
The form data are: Name, Clinic, Email, Phone, Address and Valutation.
In the email I receive the data are:
Name: name entered in the form
Email: email entered in the form
Clinic: undefined
Phone: undefined
Address: undefined
Valutation: undefined
This is the code (HTML + JS):
// JavaScript Document
$(document).ready(function() {
"use strict";
$(".contact-form").submit(function(e) {
e.preventDefault();
var name = $(".name");
var email = $(".email");
var clinic = $(".clinic");
var phone = $(".phone");
var address = $(".address");
var valutation = $(".valutation");
var subject = $(".subject");
var msg = $(".message");
var flag = false;
if (name.val() == "") {
name.closest(".form-control").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".form-control").removeClass("error").addClass("success");
}
if (email.val() == "") {
email.closest(".form-control").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".form-control").removeClass("error").addClass("success");
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&subject=" + subject.val() + "&msg=" + msg.val() + "&clinic=" + clinic.val() + "&phone=" + phone.val() + "&address=" + address.val() + "&valutation=" + valutation.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "php/contactForm.php",
cache: false,
success: function(d) {
$(".form-control").removeClass("success");
if (d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="#48af4b">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="#ff5607">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").on('click', function() {
$(".form-control").removeClass("success").removeClass("error");
});
})
<div class="row justify-content-center">
<div class="col-lg-10 col-xl-8">
<div class="form-holder">
<form class="row contact-form" method="POST" action="php/contactForm.php" id="contactForm">
<!-- Form Select -->
<div class="col-md-12 input-subject">
<p class="p-lg">This question is about: </p>
<span>How satisfied are you with the service that Lab offers? </span>
<select class="form-select subject" aria-label="Default select example" name="valutation">
<option>Very unsatisfied</option>
<option>Unsatisfied</option>
<option>Satisfied</option>
<option>Very satisfied</option>
<option selected>I don't have an opinion</option>
</select>
</div>
<!-- Contact Form Input -->
<div class="col-md-12">
<p class="p-lg">Your Name: </p>
<span>Please enter your Dentist Name: </span>
<input type="text" name="name" class="form-control name" placeholder="Your Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Clinic Name: </p>
<span>Please enter your Clinic Name: </span>
<input type="text" name="clinic" class="form-control name" placeholder="Clinic Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Your Email Address: </p>
<span>Please carefully check your email address for accuracy</span>
<input type="text" name="email" class="form-control email" placeholder="Email Address*">
</div>
<div class="col-md-12">
<p class="p-lg">Phone Number: </p>
<span>Please enter your/clinic phone number: </span>
<input type="text" name="phone" class="form-control name" placeholder="Phone Number*">
</div>
<div class="col-md-12">
<p class="p-lg">Address: </p>
<span>Please enter Clinic Address: </span>
<input type="text" name="address" class="form-control name" placeholder="Address*">
</div>
<!-- Contact Form Button -->
<div class="col-md-12 mt-15 form-btn text-right">
<button type="submit" class="btn btn-skyblue tra-grey-hover submit">Submit Request</button>
</div>
<!-- Contact Form Message -->
<div class="col-lg-12 contact-form-msg">
<span class="loading"></span>
</div>
</form>
</div>
</div>
</div>
And this is the PHP code:
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$clinic = $_REQUEST["clinic"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$valutation = $_REQUEST["valutation"];
$to = "myemail#email.com";
if (isset($email) && isset($name)) {
$email_subject = "Request to access to the Price List";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: $name<br/> Email: $email <br/> Clinic: $clinic <br/> Phone: $phone <br/> Address: $address <br/> Valutation: $valutation";
$mail = mail($to, $email_subject, $msg, $headers);
if ($mail) {
echo 'success';
} else {
echo 'failed';
}
}
?>
Your issue is your selectors. You only use classes name and email for all your inputs.
<input type="text" name="phone" class="form-control name" ...>
should actually be:
<input type="text" name="phone" class="form-control phone" ...>
and so on for all the other inputs. Change your selectors to the appropriate classNames.
Also, never just use i.e: $(".name");, $(".email"); etc. as your selectors. As you know already $(".name"); will get every class="name" in your document. Same goes for all the other selectors. Instead, use the second argument (ParentElement) that will limit the search only to the children elements of the provided parent:
var name = $(".name", this);
or rather, use attribute selectors like:
var clinic = $(`[name="clinic"]`, this);
IMPORTANT NOTE about validation:
never trust the client.
JS validation should be used minimally, just as a UX tool to help, inform the user about basic errors/typos. The real validation, as well as all the related error responses, should be handled on the backend side.
Currently your PHP seems quite open to XSS attacks.
You don't need a HTML <form> in order to send data to the server. All it takes to an attacker is to find your route/path (usually exposed via the form's action attribute), take a look at the names in the source and manually construct a HTTP request, and send dangerous arbitrary data to your server. Just so you keep in mind.
Related
I purchased several themes so that I could build two websites. the theme that I like the most comes with a non-functional contact form. I have tried to integrate the contact forms from the other themes into it but they will not work no matter what I do. I know that one of them works fine because I am using it on another site and it works with no issue. (for transparency the working form is being used in the theme that it came with.) is there a possibility that I am missing something?
I've copied and pasted the exact forms into the theme site and included the Js files that deal with the contact form and all I can get are errors when I try to test it live.
this is the code for the form:
<section id="contact" class="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<h3 class="title-normal">Contact Form</h3>
<form id="contact-form" action="contact-form.php" method="post" role="form">
<div class="error-container"></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Name</label>
<input class="form-control form-control-name" name="name" id="name" placeholder="" type="text" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Email</label>
<input class="form-control form-control-email" name="email" id="email" placeholder="" type="email" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Subject</label>
<input class="form-control form-control-subject" name="subject" id="subject" placeholder="" required>
</div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control form-control-message" name="message" id="message" placeholder="" rows="10" required></textarea>
</div>
<div class="text-right"><br>
<button class="btn btn-primary solid blank" type="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
</section>
this is a copy of the php:
<?php
//Add your information here
$recipient = "info#domain.us";
//Don't edit anything below this line
//import form information
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$name=stripslashes($name);
$email=stripslashes($email);
$subject=stripslashes($subject);
$message=stripslashes($message);
$message= "Name: $name, Subject: $subject \n\n Message: $message";
/*
Simple form validation
check to see if an email and message were entered
*/
//if no message entered and no email entered print an error
if (empty($message) && empty($email)){
print "No email address and no message was entered. <br>Please include an email and a message";
}
//if no message entered send print an error
elseif (empty($message)){
print "No message was entered.<br>Please include a message.<br>";
}
//if no email entered send print an error
elseif (empty($email)){
print "No email address was entered.<br>Please include your email. <br>";
}
//mail the form contents
if(mail("$recipient", "$subject", "$message", "From: $email" )) {
// Email has sent successfully, echo a success page.
echo '<div class="alert alert-success alert-dismissable fade in">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">×</button>
<p>Email Sent Successfully! We Will get back to you shortly</p></div>';
} else {
echo 'ERROR!';
}
here is the Js
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$subject = $form.find('.form-control-subject'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
subject: $subject.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$subject.val('');
$message.val('');
}
}
);
});
return false;
});
I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $errorMessage;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
New to PHP hence the very basic question. I'm trying to create a contact form that has a Honey Pot attribute built in. I want to check this honey pot value in both JS and PHP before submission.
Cases:
If no fields are filled out JS error don't Submit
If all fields are filled out BUT Honey Pot, Pass through JS, POST to PHP and send email
If all fields are filled out fail on JS and don't POST, HOWEVER I would like this to also be applicable to the PHP even if it's redundant just to understand PHP better.
Problem:
The JS validation is fine and I check .val of the input field. However I cannot seem to get the same validation in PHP to work.
index.html (contact form) *using jQuery Validate:
<form id="contactForm" method="GET" action="" class="contact-form" novalidate="novalidate">
<div class="input-field col s12">
<input name="name" type="text" id="name" class="validate" required/>
<label for="name">Name</label>
</div>
<div class="input-field col s12">
<input name="email" type="text" id="email" class="validate" required/>
<label for="email">E-mail</label>
</div>
<div class="input-field col s12">
<textarea name="message" id="message" class="materialize-textarea" required></textarea>
<label>Message</label>
</div>
<div class="input-field comment col s12">
<label>If you're human leave this blank:</label>
<input name="comment" type="text" id="comment" class="form-comment" />
</div>
<div class="col s12">
<button class="btn button-primary contact-submit-button waves-effect waves-light" type="submit">Send</button>
</div>
<div id="form-result"></div>
</form>
contact-form.js
$(document).ready(function () {
var contactFormResult = $('#form-result');
var contactForm = $('#contactForm');
contactFormResult.hide();
$.validator.setDefaults({
submitHandler: function () {
var nameValue = $('#name').val();
var emailValue = $('#email').val();
var messageValue = $('#message').val();
var robotValue = $('#comment').val();
console.log('contact form submission, name value: ' + nameValue, ' email value: ' + emailValue + ' message value: ' + messageValue + ' robot value: ' + robotValue);
//
// I want this to pass through JS and FAIL in PHP
//
if (robotValue = ''){
contactFormResult.text('you are a robot').fadeIn();
return false;
} else {
$.ajax({
type: "POST",
url: "contactSubmission.php",
data: {
name: nameValue,
email: emailValue,
message: messageValue,
robotTest: robotValue
}
}).done(function () {
contactForm.find("input[type=text], input[type=email], textarea").val("");
contactFormResult.text('form submitted successfully').fadeIn();
});
}
}
});
contactForm.validate();
});
contactSubmission.php
<?php
if ($_POST){
//Sanitize input data using PHP filter_var().
$nameValue = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$emailValue = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$messageValue = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$robotValue = filter_var($_POST["robotTest"], FILTER_SANITIZE_STRING);
if(!empty($robotValue){
die();
} else {
$to = 'myemail#gmail.com';
$subject = 'Subject Line';
$message = 'Name: ' .$nameValue. ' Email: ' .$emailValue.' Message: '.$messageValue;
mail($to, $subject, $message);
}
}
?>
I'm new in ajax/js/php.
I have a small contact form
<form id="contact-form" method="post" action="process.php" role="form">
<div class="messages"></div>
<div class="form-group">
<label for="form_name">First name *</label>
<input id="form_firstname" type="text" name="name" class="form-control" placeholder="Please enter your first name *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_lastname">Last name *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your last name *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
<p><strong>*</strong> These fields are required.</p>
</form>
<button type="submit" class="btn btn-info" value="Create Account">Create Account</button>
with small js and php
script.js
$("#contact-form").submit(function(event) {
// cancels the form submission
"use strict";
event.preventDefault();
submitForm();
});
function submitForm() {
// Initiate Variables With Form Content
"use strict";
var firstname = $("#form_firstname").val();
var lastname = $("#form_lastname").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.ajax({
type: "POST",
url: "process.php",
data: "name=" + firstname + lastname + "&email=" + email + "&phone=" + phone,
});
}
process.php
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$EmailTo = "name#email.com";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
} else {
echo "invalid";
}
?>
for some reason it's not working on way I would like to, not sending me emails (i know to put my email in $Emailto).
Often I was using only php form but I would like to avoid reloading page. I try to understand where I'm making error.
$('#contact-form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "process.php",
data:$(this).serialize(), //get form values
}).done(function(data){
console.log(data); // will contain success or invalid
});
});
Change your submit function to:
$(document).ready(function() {
$("#contact-form").submit(function(event){
"use strict";
event.preventDefault(); // cancels the form submission
var firstname = $("#form_firstname").val();
var lastname = $("#form_lastname").val();
var email = $("#form_email").val();
var phone = $("#form_phone").val();
$.ajax({
type: "POST",
url: "process.php",
data: {
name: firstname + lastname, //or firstname + " " + lastname if you want the first and lastname to be separated by a space
email: email,
phone: phone
}
}).done(function(data){
console.log(data); // will contain success or invalid
});
});
});
The values you were trying to get for email and phone were not properly defined (they were lacking the form_).
And you cannot use a querystring with a POST type only when using a GET type.
Wish you all a happy 2015!
I have a simple contact us php form. I am validating it with parsley.js. The validation works fine but I am receiving a lot of spam mails.
I believe if I can force the form to be submitted only if Jquery is enabled, then it should solve my problem (right?).
I'm not an expert with PhP/ Jquery and any help will be appreciated.
Here is my PHP code
<?php
// Define Variables i.e. name tag, as per form and set to empty
$contact_name = $contact_email = $contact_phone = $contact_message = "";
// Sanitize data and use friendly names
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["contact_name"]);
$email = test_input($_POST["contact_email"]);
$phone = test_input($_POST["contact_phone"]);
$message = test_input($_POST["contact_message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Set values
$to = 'info#foryourservice.in';
$subject = 'New Message from Website';
$headers = 'From: info#domainname.com' . "\r\n" .
'Reply-To: info#domainname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Set Email content
$emailcontent = "A new message has been submitted from the website.
\n
Name : $name
Email : $email
Phone : $phone
Message : $message";
// Mail function
$send_contact=mail($to,$subject,$emailcontent,$headers);
if($send_contact){
header('Location: index.php#contactusform');
}
else {
echo "<script type='text/javascript'>alert('We encountered an ERROR! Please go back and try again.');</script>";
}
?>
Here is my HTML ( Im using Twitter Bootstrap)
<form role="form" method="POST" action="contactusform.php" id="contactusform" data-parsley-validate>
<div class="col-xs-6">
<div class="form-group" style="margin-bottom: -5px">
<label for="input1"></label>
<input type="text" name="contact_name" class="form-control" id="input1" placeholder="Name*" required data-parsley-required-message="Please enter your name">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input2"></label>
<input type="email" name="contact_email" class="form-control" id="input2" placeholder="Email Address*" data-parsley-trigger="change" required data-parsley-required-message="Please enter a valid Email address">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input3"></label>
<input type="tel" name="contact_phone" class="form-control" id="input3" placeholder="Phone Number*" required data-parsley-type="digits" data-parsley-minlength="10" data-parsley-maxlength="10" data-parsley-required-message="Please enter a 10 digit number">
</div>
<br>
<div class="form-group">
<button type="submit" id="contactbutton" class="btn btn-primary" style="background-color: #A8B645; border-color: transparent">Submit</button>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="input4"></label>
<textarea name="contact_message" class="form-control" rows="7" id="input4" placeholder="Message*" required required data-parsley-required-message="Say something!"></textarea>
</div>
</div>
</form>
This is what the Spam Email looks like :
A new message has been submitted from the website.
Name : お買い得アナスイ ミロード大壳り出しランキング
Email : rsilau#gmail.com
Phone : お買い得アナスイ ミロード大壳り出しランキング
Message : Shoppers takes the boast on bag
お買い得アナスイ ミロード大壳り出しランキング http://www.frkapaun.org/dyqfmnwg/ysl-annasuixmraAekm.asp
Add a hidden field to your form:
<input type="hidden" value="0" id="botcheck" name="botcheck" />
Then with jQuery set the value to 1:
$("#botcheck").val("1");
Then server-side check the value of $_POST["botcheck"].
You might want to check if your form is submitted using ajax:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Process form here
}
For further explanation