I need help to fix a blank emails from my form - javascript

I'm getting everyday in around the same hour 6 blank emails from my contact form, if I fill the form in the website all the info go through and I'm getting the email with the details, I have a validation for my form but still getting the blank emails. What do I need to do?
At the beginning I was getting an error for some lines in my php but it's already fixed but I'm still getting the blank emails.
This is My PHP code:
$fname = $lname = $email = $tel = $address = $project = $message = '';
if (isset($_POST['fname'])) {
$fname = $_POST['fname'];
}
if (isset($_POST['lname'])) {
$lname = $_POST['lname'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
if (isset($_POST['tel'])) {
$tel = $_POST['tel'];
}
if (isset($_POST['address'])) {
$address = $_POST['address'];
}
if (isset($_POST['project'])) {
$project = $_POST['project'];
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
$to = '...';
$email_subject = "$fname $lname Contact You from ... :";
$email_body = "You have received a new message from your website contact form.<br/>"."Here are the details:<br/><br/> Name: $fname $lname<br/> Email: $email<br/> Phone: $tel<br/> Address: $address<br/> Project: $project<br/> Message:\n$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: ...' . "\r\n";
$headers .= 'Reply-To: ...' . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if(mail($to,$email_subject,$email_body,$headers)) {
echo "OK";
}
This Is my HTML code:
<form action="" method="post" role="form" class="contactForm" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-6 form-group">
<label for="fname">First Name*</label>
<input type="text" class="form-control" name="fname" id="fname" data-rule="minlen:3" data-msg="*Please Enter at Least 3 Chars" />
<div class="validation"></div>
</div>
<div class="col-lg-6 form-group">
<label for="lname">Last Name*</label>
<input type="text" class="form-control" name="lname" id="lname" data-rule="minlen:3" data-msg="*Please Enter at Least 3 Chars" />
<div class="validation"></div>
</div>
<div class="col-lg-6 form-group">
<label for="tel">Phone Number*</label>
<input type="tel" class="form-control" name="tel" id="tel" data-rule="minlen:10" data-msg="*Please Enter a Valid Phone Number" />
<div class="validation"></div>
</div>
<div class="col-lg-6 form-group">
<label for="email">Email Address*</label>
<input type="email" class="form-control" name="email" id="email" data-rule="email" data-msg="*Please Enter a Valid Email Address" />
<div class="validation"></div>
</div>
<div class="col-lg-12 form-group">
<label for="address">Location (Address)</label>
<input type="text" class="form-control" name="address" id="address" />
<div class="validation"></div>
</div>
<div class="col-lg-12 form-group">
<label for="project">Select Project / Service</label>
<select type="text" class="form-control" name="project" id="project">
<option selected value="">Select Project</option>
<option value="Emergency HVAC Service">Emergency HVAC Service</option>
<option value="Air Conditioner Installation">Air Conditioner Installation</option>
<option value="Air Conditioner Repair">Air Conditioner Repair</option>
<option value="Air Conditioner Replacement">Air Conditioner Replacement</option>
<option value="Duct Repair">Duct Repair</option>
<option value="Duct Replacement">Duct Replacement</option>
<option value="Furnace Repair">Furnace Repair</option>
<option value="HVAC Maintenance">HVAC Maintenance</option>
<option value="Air Duct Cleaning">Air Duct Cleaning</option>
</select>
<div class="validation"></div>
</div>
<div class="col-lg-12 form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message" id="message"></textarea>
<div class="validation"></div>
</div>
<div id="hide-button" class="col-lg-12 text-center">
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
<div class="col-lg-10 offset-lg-1 text-center">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage">Sorry! Something went wrong. Try again.</div>
</div>
</div>
</form>
Javascript Validation:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (!i.attr('checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'mail/mailer.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
// alert(msg);
if (msg == 'OK') {
$('#hide-button').addClass("hide");
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$('#hide-button').removeClass("hide");
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
}
}
});
return false;
});
});
Tell me if I need to add my jQuery.
I'm very familiar with html and css but not that much with PHP and Javascript.

It looks like you have client-side validation in the form of some JavaScript/jQuery stuff, but the fact is that you can't trust the client. Client-side validation is there to help the user, but must not be relied on by the server.
Someone can craft a POST request to your form processing PHP script without using a browser at all, so they can send any old data they like. Probably what you're seeing is emails from some crawler bot or similar doing exactly this.
So, you need to add some similar validation logic to your PHP code (which is obviously on the server side, and therefore much more trustworthy than code on the client side). For example, to check the lname field isn't blank, you could do:
if (empty($lname)) {
showErrorPage('Please enter a last name!');
exit; // To halt processing.
}

Related

email file attachment php, Ajax, Jquery

i have problem with email file attachment php, Ajax, Jquery on the following codes, also i need the file attachment field mandatory. the uploaded file in the form doesn't pass to the email!
i need to place code into the Ajax to receive file(s) from the form and check the empty field, then it everything goes fine pass the fields include file(s) to the form. and from the form to the Email.
HTML Form:
<form role="form">
<div class="form-group">
<label for="inputName" class="form-label "></label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail" class="form-label "></label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage" class="form-label "></label>
<input type="text" class="form-control" id="inputMessage" placeholder="Phone Example:+1234567890"></textarea>
</div>
</form>
<button type="button" class="btn sign-btn-primary submitBtn" onclick="submitContactForm()">Request</button>
<p class="statusMsg"></p>
my php file :
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'info#test.org';
$subject= 'CCI2017 Download Log';
$htmlContent = '
<h4>The CCI 2017 has been downloaded by person, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Phone:</th><td>'.$message.'</td>
</tr>
</table>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: ME' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
my jquery:
<script type="application/javascript">
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (message.trim() != '' && !regp.test(message)) {
alert('Please enter your Phone.');
$('#inputMessage').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_form.php',
data: 'contactFrmSubmit=1&name=' + name + '&email=' + email + '&message=' + message,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
if (msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('Download');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Solutions:
<form role="form">
<div class="form-group">
<label for="inputName" class="form-label "></label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail" class="form-label "></label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage" class="form-label "></label>
<input type="text" class="form-control" id="inputMessage" placeholder="Phone Example:+1234567890"></textarea>
</div>
</form>
<button type="button" class="btn sign-btn-primary submitBtn" onclick="submitContactForm()">Request</button>
<p class="statusMsg"></p>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="application/javascript">
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var regp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if (name.trim() == '') {
alert('Please enter your name.');
$('#inputName').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (message.trim() != '' && !regp.test(message)) {
alert('Please enter your Phone.');
$('#inputMessage').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_form.php',
data: 'contactFrmSubmit=1&name=' + name + '&email=' + email + '&message=' + message,
beforeSend: function () {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function (msg) {
if (msg == 'ok') {
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('Download');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Submit_form.php
<?php
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
$to = 'kiran.mind2014#gmail.com';
// Subject
$subject = 'CCI2017 Download Log';
// Message
$message = '
<h4>The CCI 2017 has been downloaded by person, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Phone:</th><td>'.$message.'</td>
</tr>
</table>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Kiran <kiran.mind2014#gmail.com>';
$headers[] = 'From: CCI2017 Download Log <kiran.mind2014#gmail.com>';
// Send email
if(mail($to, $subject, $message, implode("\r\n", $headers))){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
It is working fine!!!.

Javascript is hanging up and takes almost 2 minutes to process form

I have a form up on http://coreelectric.us/contact.php that takes 2 minutes to process. On my localhost it is instantaneous. However, when I put the site live it takes forever. Here is the code in the form itself...
<form action="" method="post" class="form-content" id="contact-form" >
<div class="form-container">
<div id="thanks">Your email was sent successfully. Thank you, we will contact you soon.</div>
<div class="input-form">
<div class="input-left">
<label>*First Name :</label>
<input id="fname" type="text" name="fname" placeholder="Enter your first name" />
</div>
<div class="input-right">
<label>*Last Name :</label>
<input id="lname" type="text" name="lname" placeholder="Enter your last name" />
</div>
<div class="clearfix"></div>
</div>
<div class="input-form">
<div class="input-left">
<label>*Email :</label>
<input id="email" type="text" name="email" placeholder="Enter your valid email address " />
</div>
<div class="input-right">
<label>Phone Number :</label>
<input id="phone" type="text" name="phone" placeholder="Enter your phone only digit" />
</div>
<div class="clearfix"></div>
</div>
<div class="input-form">
<label>*Subject :</label>
<input id="subject" type="text" name="subject" placeholder="Subject"/>
<div class="clearfix"></div>
</div>
<div class="input-form">
<label>*Message :</label>
<textarea id="message" name="message" rows="10" placeholder="Enter your message here"></textarea>
</div>
<div class="input-form">
<label>*You must authenticate:</label>
<div style="float: left;" class="g-recaptcha" id="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" data-callback="onReturnCallback" data-theme="light"></div>
</div>
<input type="submit" style="float: right;" class="btn st-btn btn-rounded btn-primary" value="Submit" />
<div class="error-msg"></div>
</div>
</form>
The javascript being used to process it is...
<script>
document.getElementById('phone').addEventListener('input', function (evt) {
evt.target.value = evt.target.value.replace(/\D/g, '');
});
$(document).on("keyup", "input.error", function(){
phone=$('#phone').val();
if($.isNumeric(phone)){
$('#phone').removeClass("error");
}
});
$(document).ready(function(){
$('#contact-form').submit(function(){
$('#contact-form .error').removeClass('error');
$('#contact-form .error-msg').hide()
form = true;
elm = $(this);
fname = $('#fname').val();
lname = $('#lname').val();
howhear = $('#how_hear').val();
state = $('#state').val();
street = $('#street').val();
city = $('#city').val();
zip = $('#zcode').val();
subject = $('#subject').val();
address = $('#address').val();
email = $('#email').val();
phone = $('#phone').val();
message = $('#message').val();
email_regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email == ''){
$('#email').addClass('error');
form = false;
}else if(email_regex.test(email) == false){
$('#email').addClass('error');
form = false;
}
if(fname==''){
$('#fname').addClass('error');
form = false;
}
if(lname==''){
$('#lname').addClass('error');
form = false;
}
if(subject==''){
$('#subject').addClass('error');
form = false;
}
if(phone==''){
$('#phone').addClass('error');
form = false;
}
if(howhear==''){
$('#how_hear').addClass('error');
form = false;
}
if(state==''){
$('#state').addClass('error');
form = false;
}
if(street==''){
$('#street').addClass('error');
form = false;
}
if(zip==''){
$('#zcode').addClass('error');
form = false;
}
if(address==''){
$('#address').addClass('error');
form = false;
}
if(city==''){
$('#city').addClass('error');
form = false;
}
if(howhear==''){
$('#how_hear').addClass('error');
form = false;
}
if(message==''){
$('#message').addClass('error');
form = false;
}
if(grecaptcha.getResponse() ==""){
$('#g-recaptcha').addClass('error');
$('.error-msg').html('*Captcha ').show();
form = false;
}
if(form == false){
$('.error-msg').html('*Please filled correctly highlighted fields').show();
}
if(form){
$.ajax({
url:'email.php',
type:'post',
data: $('#contact-form').serialize(),
success: function(res){
$('#thanks').show();
setTimeout(function() {
$('#thanks').fadeOut('fast');
}, 60000); // <-- time in milliseconds
$('#contact-form')[0].reset();
}
});
}
return false;
});
});
</script>
the process page contains the following...
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$name = $fname." ".$lname;
$street = $_POST['street'];
$city = $_POST['city'];
$zip = $_POST['zcode'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$how_hear = $_POST['how_hear'];
$newsletter = $_POST['newsletter'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$domain = $_SERVER['SERVER_NAME'];
$to = "receiver#mydomain.com, ".$email;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From:".$email . "\r\n";
$headers .= "BCC: myemail#mydomain.com, another#mydomain.com \r\n";
$txt = '<html style="background-color:#68B7F4">'
. '<div style="background-color:#FFF; padding: 10px;"><img
src="http://coreelectric.us/images/logo.png" alt="Core Electric" >
</div>'
. '<div>An email has been received from the contact page at
'.$domain.'. The following information was provided:<br><br></div>'
. '<table width="100%"><tr><td style="text-align: right; width:
15%;">Name: </td><td style="text-align: left; width:
85%;">'.$name.'</td></tr>'
. '<tr><td style="text-align: right; width: 15%;">Phone: </td><td
style="text-align: left; width: 85%;">'.$phone.'</td></tr>'
. '<tr><td style="text-align: right; width: 15%;">Email: </td><td
style="text-align: left; width: 85%;">'.$email.'</td></tr>'
. '<tr><td style="text-align: right; vertical-align: top; width:
15%;">Message: </td><td style="text-align: left; width:
85%;">'.$message.'</td></tr></table>'
. '<br><br>A representative will be in contact with you within 24
hours.'
. '</html>';
mail($to,$subject,$txt,$headers);
I'd truly appreciate any help understanding what could possibly be causing the hangup. It hangs up between these 2 lines of javascript...
data: $('#contact-form').serialize(),
success: function(res){
Thanks in advance
if(form){
console.log(Date.now())
$.ajax({
url:'email.php',
type:'post',
data: $('#contact-form').serialize(),
success: function(res){
console.log(Date.now())
console.log(res)
$('#thanks').show();
setTimeout(function() {
$('#thanks').fadeOut('fast');
}, 60000); // <-- time in milliseconds
$('#contact-form')[0].reset();
},
error: function(error) {
console.log(Date.now())
console.log(error)
}
});
}
and the php
if(mail($to,$subject,$txt,$headers)) {
echo "OK";
} else {
echo "Whoops";
}
By that, you might at least determine where is the problem. Also you might try to remove the if in php and try if error function in javascript won't catch a php error.
I ran my original code on a different server where I'm now running the same form on 3 different sites and it is lightning fast... narrowed it down to some issue with the other server, that i have zero interest in troubleshooting. I believe this one is closed. Thank you for the input.

Perform two task with jQuery and php

I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.

Trying to use PHP and Ajax to do form validation, not working

I have been trying to figure out how to do php form validation and using ajax to get the results back so I don't have to refresh page. I'm new to ajax and having a hard time.
This is my registration.php form
<h1>Sign Up</h1>
<form id="registration_form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First name</label>
<input type="text" class="form-control" id="first_name" name="first_name" onblur="validate('first_name', this.value)" placeholder="First name">
</div>
</div>
<div id="textFirstName" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="last_name">Last name</label>
<input type="text" class="form-control" id="last_name" name="last_name" onblur="validate('last_name', this.value)" placeholder="Last name">
</div>
</div>
<div id="textLastName" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email1">Email address</label>
<input type="email" class="form-control" id="email1" name="email1" onblur="validate('email1', this.value)" placeholder="Email">
</div>
</div>
<div id="textEmail" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Password1">Password</label>
<input type="password" class="form-control" id="password1" name="password1" onblur="validate('password1', this.value)" placeholder="Password">
</div>
</div>
<div id="textPass1" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Password2">Confirm Password</label>
<input type="password" class="form-control" id="password2" name="password2" onblur="validate('password2', this.value)" placeholder="Retype Password">
</div>
</div>
<div id="textPass2" class="col-md-6">
</div>
</div>
<div class="row">
<div class="col-md-6">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="col-md-6">
</div>
</div>
</form>
This is my validation php script:
<?php
$value = $_POST['query'];
$formfield = $_POST['field'];
// Check Valid or Invalid first name when user enters user name in username input field.
if ($formfield == "first_name") {
if (strlen($value) < 1) {
echo "<p style=\"color:red\">Error: Must be 1+ letters</p>";
} else {
echo "<p style=\"color:green\">Valid</p>";
$_SESSION['reg']['first_name'] = $value;
}
}
if ($formfield == "last_name") {
if (strlen($value) < 1) {
echo "<p style=\"color:red\">Error: Must be 1+ letters</p>";
} else {
echo "<p style=\"color:green\">Valid</p>";
$_SESSION['reg']['last_name'] = $value;
}
}
// Check Valid or Invalid password when user enters password in password input field.
if ($formfield == "password1") {
if (strlen($value) < 8) {
echo "<p style=\"color:red\">Error: Password too short. Must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if (!preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $value)){
echo "<p style=\"color:red\">Error: Your password must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else {
echo "<p style=\"color:green\">Your password is good.</p>";
$_SESSION['reg']['password1'] = $value;
}
}
if ($formfield == "password2") {
if (strlen($value) < 8) {
echo "<p style=\"color:red\">Error: Password too short. Must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if (!preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $value)){
echo "<p style=\"color:red\">Error: Your password must be at least 8 characters long, contain one lower case letter, one uppercase letter, and one number.</p>";
}
else if ($_SESSION['password1'] != $value) {
echo "<p style=\"color:red\">Error: Your passwords don't match.</p>";
}
else {
echo "<p style=\"color:green\">Your password is good.</p>";
}
}
// Check Valid or Invalid email when user enters email in email input field.
if ($formfield == "email1") {
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $value)) {
echo "<p style=\"color:red\">Invalid email.</p>";
} else {
echo "<p style=\"color:red\">Valid</p>";
$_SESSION['reg']['email1'] = $value;
}
}
?>
And this is my javascript file with the ajax:
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var password1 = document.getElementById("password1").value;
var password2 = document.getElementById("password2").value;
var email = document.getElementById("email1").value;
//Check input Fields Should not be blanks.
if (first_name == '' || last_name == '' || password1 == '' || password2 == '' || email1 == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var textFirstName = document.getElementById("first_name");
var textLastName = document.getElementById("last_name");
var textPass1 = document.getElementById("password1");
var textPass2 = document.getElementById("password2");
var textEmail = document.getElementById("email1");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
str1 = textFirstName.innerHTML; str2 = textLastName.innerHTML; str3 = textPass1.innerHTML; str4 = textPass2.innerHTML; str5 = textEmail.innerHTML;
if (str1.substr(0,4) == 'Error' || str2.substr(0,4) == 'Error' || str3.substr(0,4) == 'Error' || str4.substr(0,4) == 'Error' || str5.substr(0,4) == 'Error') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("POST", "lib/validate_registration_form.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
When I enter values in the form there is no response regardless of whether i input valid or invalid information. I am sure the problem lies in the JS file with the ajax, but I don't know what it is. Any help would be greatly appreciated.
You have two issue :
First, in your html/javascript the onblur event calls
validate('first_name', this.value)
But there is not HTML element with ID = first_name, your div is called textFirstName
So you should change your onblur with proper parameter value such as
validate('textFirstName', this.value)
Next, you use POST method for your ajax but send your parameter in the URL which are stored in the $_GET array
Change :
<?php
$value = $_POST['query'];
$formfield = $_POST['field'];
To :
<?php
$value = $_GET['query'];
$formfield = $_GET['field'];
Final note : you may want to use isset($_GET['query']) in your php script to avoid notice message of undefined or at least a way to debug :
if (!isset($_GET['query']))
{
die ("missing parameter, report to admin that he should debug the JS");
}
EDIT
Following your comment, here is how to send POST data
var params = "field=" + field + "&query=" + query;
xmlhttp.open("POST", "lib/validate_registration_form.php", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);

Form to different recipients based on radio button input

I cant think anymore, stuck trying to make this work. I've got two radio buttons, how do I send the form to one of two email adresses depending on the button clicked. I am a total idiot on php, thank you.
html
<div class="col-md-8 contact-top">
<h3>Book here Online!</h3>
<form method="post" action="FormtoEmail/FormtoEmail.php">
<form role="form">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Name">
</div> <div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="subject" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1">Booking Accommodation</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2" >Booking Conference</label>
</div>
<div class="form-group">
<textarea rows="11" name="message" id="message" class="form-control" placeholder="Details"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
my php
<?php
$my_email = "info#westcoastwebdesign.biz";
$continue = "/";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Check all fields for an email header.
function recursive_array_check_header($element_value)
{
global $set;
if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);}
}
}
recursive_array_check_header($_REQUEST);
if($set){$errors[] = "You cannot send an email header";}
unset($set);
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";}
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."";
$message = stripslashes($message);
$subject = "Out of Africa Town Lodge Contact Form";
$headers = "From: " . $_POST['email'];
$recipients = array(
'recipient_1' => 'info#westcoastwebdesign.biz',
'recipient_2' => 'westcoastwebdesign77#gmail.com'
);
$my_email = $recipients[$_REQUEST['recipient']];
mail($my_email,$subject,$message,$headers);
?>
You need to use a radio button group with same name but value with different email id
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1#email.com">
Booking Accommodation
</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2#email.com" >
Booking Conference
</label>
</div>
That way you can select one from two radio
in FormtoEmail.php
//use post to get the email id
$to = $_POST['recipients'];
and send mail using PHPMailer, its great library and will make your life easier
May you want use this code:
<?php
if(isset($_POST['recipients']) && $_POST['recipients'] == 'recipient_1') {
// send to recipient_1
} else {
// send to recipient_2
}
?>
$my_email = $recipients[$_REQUEST['recipient']];
There is a typo in $_REQUEST variable, it would be $recipients[$_REQUEST['recipients']];
Hope it will work now. It could be more easily done in anyway.

Categories

Resources