Contact Form missing (send.php file) - javascript

Hi i would just like to ask some help regarding my contact form because I do not know how to create a php script to run on submit my form (send.php). Here my code for the Contact Form:
<div class="contact_form_holder">
<form id="contact" class="row" name="form1" method="post" action="#">
<div class="span4">
<label>Nom</label>
<input type="text" class="full" name="name" id="name" />
</div>
<div class="span4">
<label>Email <span class="req">*</span></label>
<input type="text" class="full" name="email" id="email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span8">
<label>Message <span class="req">*</span></label>
<textarea cols="10" rows="10" name="message" id="message" class="full"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send" class="btn btn-large" /></p>
</div>
</form>
</div>
Here my Javascript:
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var error = false;
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}else{
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "You Got Email" + "&message=" + message,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
I'm guessing i need the url : "send.php", Thank you so much in advance.

you should give your action page where you are receiving your data. your code could be like this..
<form id="contact" class="row" name="form1" method="post" action="send.php">

First of all actually submits the surrounding form.
Use Because it does nothing next to submit.
Secondly in your ajax call you have written :
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}
});
The if condition is invalid if the value of data is not 'success'. I don't know whether it is returning success or not.
So lastly change input type submit to input type button .. hope it will work..

Make a file name with "send.php" in the same root where it's html file exist.
and some php code here ...
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: webmaster#example.com" . "\r\n" .
//mail(to,subject,message,headers,parameters);
mail($email,$subject,$message,$headers);

Related

Undefined data in the email of my contact form

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.

Submit button does not work, how to make it work? (code provided in description)

I am trying to make this code work, and have tried many things (some of which I also found in StackOverflow), but nothing works. When I click on "Send Message" (submit button to send the contact info), absolutely nothing happens.
HTML:
<!-- CONTACT FORM -->
<form method="post" class="wow fadeInUp" id="contact-form">
<!-- IF MAIL SENT SUCCESSFUL -->
<h6 class="text-success">Your message has been sent successfully.</h6>
<!-- IF MAIL NOT SENT -->
<h6 class="text-danger">E-mail must be valid and message must be longer than 1 character.</h6>
<div class="col-md-6 col-sm-6">
<input type="text" class="form-control" id="cf-name" name="name" placeholder="Full name">
</div>
<div class="col-md-6 col-sm-6">
<input type="email" class="form-control" id="cf-email" name="email" placeholder="Email address">
</div>
<div class="col-md-12 col-sm-12">
<input type="text" class="form-control" id="cf-subject" name="subject" placeholder="Subject">
<textarea class="form-control" rows="6" id="cf-message" name="message" placeholder="Message"></textarea>
<button type="submit" class="form-control" id="cf-submit" name="submit">Send Message</button>
</div>
</form>
JS:
// CONTACT FORM
$("#contact-form").submit(function (e) {
e.preventDefault();
var name = $("#cf-name").val();
var email = $("#cf-email").val();
var subject = $("#cf-subject").val();
var message = $("#cf-message").val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "contact.php"
data: dataString,
success: function () {
$('.text-success').fadeIn(1000);
//$('.text-danger').fadeOut(500);
}
});
}
else {
$('.text-danger').fadeIn(1000);
//$('.text-success').fadeOut(500);
}
return false;
});
contact.php:
<?php
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['subject']) &&
isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
mail( "davidchau#gmail.com", "Contact Form: ". $_POST['name'], $_POST['subject'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
I have the JS script inside the body of the HTML (at the end of the body). Any help is greatly appreciated.

Form submission success message not displaying

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();
}

On form submission hide the form diva and send an email using jQuery

My objective is to send the form data as an email using php and the form div should get replaced by another div. I have done hiding the div part using jquery but not able to send and email. I have also written the code to send email but my issue is how to call the file which has email sending code.
My form code:
<form method="post" id="formsub">
<div id="form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="text" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
</div>
<div class="form-group">
<input type="button" id="addbut" name="submit" value="Submit" class="form-control">
</div>
</div>
</form>
My code to hide the div and tried form submission script:
<script>
$(document).ready(function() {
$("#addbut").on('click', function() {
$.ajax({
type: "POST",
url: "fromemail.php",
data: $(form).serialize(),
success: function(){
$("#form").hide();
$("#address").show();
}
});
});
});
</script>
My php email sending code:
<?php
if($_POST['submit']){
$to = "akhil#redd.xyz"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$phone = $_POST['phone'];
$subject = "Spots Contact";
$message = $first_name . ", with " . $phone . "has enquired for the service";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
if(mail($to,$subject,$message,$headers))
{
echo "<script>alert('We will contact you shortly');</script>";
}
}
?>
Give file name in form action attribute :
<form id="formsub" method="post" action="fromemail.php">
and do ajax code like this :
$(document).ready(function(){
var form=$("#formsub");
$("#addbut").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#formsub").serialize(),
success: function(response){
console.log(response);
}
});
});
});
#Rakhi..
Is this correct??
<script type="text/javascript" src="assets/js/jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function() {
var form=$("#formsub");
var base_url = "www.3ding.in/spots/";
$("#addbut").on('click', function() {
$("#form").hide();
$("#address").show();
$.ajax({
type: "POST",
url: base_url + "fromemail.php",
data: $("#formsub").serialize(),
success: function(response){
alert(1);
console.log(response);
}
});
});
});

PHP Contact Form Submission (Honey Pot)

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);
}
}
?>

Categories