I have looked all over the internet and searched through questions here and haven't been able to find a solution to get recaptcha to validate. I am using 3 files for my form, Html file, JS file for validation(bootstrapValidator) and php file for sending mail which is with phpmailer. The form works sending the mail out and clearing the form when sumbitted. I do have the captcha inserted in the form.
What I'm trying to figure out is how to get recaptcha to work with the form properly. Right now when I hit send and no fields filled in shows errors, not on captcha. Once fields are filled in properly then errors are removed. Hit send and it will send the information to the to address. Just haven't been able to get recaptcha to work with form so when hit send and captcha is not checked then form won't be sent.
This is just one of the ways I have tried validating by putting it on my php form at the top right above date_default_timezone_set('Etc/UTC'); with no luck
if(isset($_POST['submit']) && !empty($_POST['submit'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = 'your secret key';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
Here is HTML file:
<form class="form-horizontal" action="" method="post" id="contact_form">
Set Up An Appointment
<div class="col-md-12">
<div class="allFields">* ALL FIELDS REQUIRED *</div>
</div>
<div id="mainContent" class="col-sm-12">
<!-- Full Name -->
<div class="form-group">
<label for="fullname" class="col-md-4 control-label">Full Name*</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="Full Name" name="fullname" class="form-control">
</div>
</div>
</div>
<!-- Address -->
<div class="form-group">
<label for="address" class="col-md-4 control-label">Address</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-road"></i></span>
<input type="text" placeholder="Address" name="address" class="form-control">
</div>
</div>
</div>
<!-- City -->
<div class="form-group">
<label for="city" class="col-md-4 control-label">City</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
<input type="text" placeholder="City" name="city" class="form-control">
</div>
</div>
</div>
<!-- State -->
<div class="form-group">
<label class="col-md-4 control-label">State</label>
<div class="col-md-5 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
<select name="state" class="form-control selectpicker" >
<option value=" " >Please select your state</option>
<option>Ohio</option>
<option>Pennsylvania</option>
</select>
</div>
</div>
</div>
<!-- Zip Code -->
<div class="form-group">
<label for="zipcode" class="col-md-4 control-label">Zip Code</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span>
<input type="text" placeholder="Zip Code" name="zipcode" class="form-control">
</div>
</div>
</div>
<!-- Phone -->
<div class="form-group">
<label for="phone" class="col-md-4 control-label">Phone #</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input type="text" placeholder="(330)222-2222" name="phone" class="form-control">
</div>
</div>
</div>
<!-- Email -->
<div class="form-group">
<label for="email" class="col-md-4 control-label">E-mail</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" placeholder="E-mail Address" name="email" class="form-control">
</div>
</div>
</div>
<!-- Appointment Reason -->
<div class="form-group">
<label class="col-md-4 control-label">Appt Reason</label>
<div class="col-md-5 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
<select name="reason" class="form-control selectpicker" >
<option value=" ">Select Your Appointment Reason</option>
<option>Roofing</option>
<option>Siding</option>
<option>Doors</option>
<option>Windows</option>
<option>Decking</option>
<option>Comfort Rooms</option>
<option>Kitchen</option>
</select>
</div>
</div>
</div>
<!-- Appointment Date -->
<div class="form-group">
<label class="col-md-4 control-label">Appt. Date</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group date" id="datepicker">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
<input type="text" placeholder="Date you would like Appointment" name="apptDate" class="form-control">
</div>
</div>
</div>
<!-- Appointment Time -->
<div class="form-group">
<label class="col-md-4 control-label">Appt. Time</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group date" id="timepicker">
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
<input type="text" placeholder="Time you would like Appointment" name="apptTime" class="form-control">
</div>
</div>
</div>
<!-- Contact Method -->
<div class="form-group">
<label class="col-md-4 control-label">Contact You</label>
<div class="col-md-5 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
<select name="method" class="form-control selectpicker" >
<option value=" ">Select Your Contact Method</option>
<option>Email</option>
<option>Phone</option>
</select>
</div>
</div>
</div>
<!-- Project Description -->
<div class="form-group">
<label for="comments" class="col-md-4 control-label">Project Description</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea name="comments" placeholder="Project Description" rows="5" class="form-control"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Captcha</label>
<div class="col-md-5 inputGroupContainer">
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-5" id="captchaMessage"></div>
</div>
<!-- Submit Button -->
<div class="form-group">
<div class="col-md-offset-4 col-md-5">
<button type="submit" name="submit" class="btn btn-primary">Send <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</div> <!-- mainContent -->
</fieldset>
</form>
JS File:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function(validator, form, submitButton) {
$.ajax({
type: "POST",
url: "appt.php",
data: $('#contact_form').serialize(),
success: function(){
$('#contact_form').each(function(){
this.reset();
$(contact_form).data('bootstrapValidator').resetForm();
});
},
error: function(){
alert("error");
}
});//close ajax
},
fields: {
fullname: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'Please supply your full name'
}
}
},
address: {
validators: {
stringLength: {
min: 8,
},
notEmpty: {
message: 'Please supply your street address'
}
}
},
city: {
validators: {
stringLength: {
min: 4,
},
notEmpty: {
message: 'Please supply your city'
}
}
},
state: {
validators: {
notEmpty: {
message: 'Please select your state'
}
}
},
zipcode: {
validators: {
stringLength: {
min: 5,
},
notEmpty: {
message: 'Please supply your zip code'
},
zipCode: {
country: 'US',
message: 'Please supply a vaild zip code'
}
}
},
phone: {
validators: {
notEmpty: {
message: 'Please supply your phone number'
},
phone: {
country: 'US',
message: 'Please supply a vaild phone number with area code'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Please supply your email address'
},
emailAddress: {
message: 'Please supply a valid email address'
}
}
},
reason: {
validators: {
notEmpty: {
message: 'Please select what your appointment is for'
}
}
},
method: {
validators: {
notEmpty: {
message: 'Please select your preferred contact method'
}
}
},
comments: {
validators: {
stringLength: {
min: 10,
max: 200,
message:'Please enter at least 10 characters and no more than 200'
},
notEmpty: {
message: 'Please supply a description of your project'
}
}
},
}
})
});
PHP File to send:
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
//Contact Form Data
$fullnameField = $_POST['fullname'];
$addressField = $_POST['address'];
$cityField = $_POST['city'];
$stateField = $_POST['state'];
$zipcodeField = $_POST['zipcode'];
$phoneField = $_POST['phone'];
$emailField = $_POST['email'];
$apptReasonField = $_POST['reason'];
$apptDateField = $_POST['apptDate'];
$apptTimeField = $_POST['apptTime'];
$methodField = $_POST['method'];
$commentsField = $_POST['comments'];
require 'mailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.aol.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "xxxxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxxxxxx";
//Set who the message is to be sent from
$mail->setFrom('xxxxxxxx');
//Set who the message is to be sent to
$mail->addAddress('xxxxxxxxxx');
//Set the subject line
$mail->Subject = 'Information For Appointment Wanted';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->Body = <<<EOD
<br><p>Here is the information $fullnameField entered in your Appointment form.</p>
<br><hr><br>
<b>Name:</b> $fullnameField<hr><br>
<b>Address:</b> $addressField<hr><br>
<b>City:</b> $cityField<hr><br>
<b>State:</b> $stateField<hr><br>
<b>Zip Code:</b> $zipcodeField<hr><br>
<b>Phone #:</b> $phoneField<hr><br>
<b>E-mail:</b> $emailField<hr><br>
<b>Appointment Reason:</b> $apptReasonField<hr><br>
<b>Date Wanted For Appointment:</b> $apptDateField<hr><br>
<b>Time Wanted For Appointment:</b> $apptTimeField<hr><br>
<b>Best Way To Contact You:</b> $methodField<hr><br>
<b>Project Description:</b> $commentsField<hr><br>
EOD;
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "Message has been sent";
}
?>
You are essentially trying to extend your client side validation to include your reCaptcha. Since the reCaptcha isn't an input I don't believe you can extend your Bootstrap validator very easily. You can however add some additional javascript to add this validation.
You need some javascript variable to keep track of whether your reCaptcha has been solved:
var captcha_passed = false;
Tell Google's reCaptcha to call your function upon successful completion:
<div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
Add another label to let your users know that this was missed. Make it hidden. The javascript will unhide it if they submit without the reCaptcha.
<div class="form-group">
<label class="col-md-4 control-label">Captcha</label>
<div class="col-md-5 inputGroupContainer">
<div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
<label id="lblCaptchaRequired" hidden>Please complete the reCaptcha</label>
</div>
Add javascript function to be called by the reCaptcha:
/*
* Google reCaptcha data-callback handler.
* Sets captcha_passed to true to allow form submission and hides captcha required label.
*/
function on_captcha_filled() {
captch_passed = true;
$('#lblCaptchaRequired').hidden = true;
}
Add a check to your submit handler to verify that the reCaptcha has passed:
submitHandler: function(validator, form, submitButton) {
if (captcha_passed) {
$.ajax({
type: "POST",
url: "appt.php",
data: $('#contact_form').serialize(),
success: function(){
$('#contact_form').each(function(){
this.reset();
$(contact_form).data('bootstrapValidator').resetForm();
});
},
error: function(){
alert("error");
}
});//close ajax
}
else {
$('#lblCaptchaRequired').hidden = false;
}
},
Now when your user attempts to submit without first completing the reCaptcha they will be notified and the form will not submit.
Related
Hi i have a class using needs validate in form is there a way for me to validate this on button submit onclick ? or a better way to improve the coding for this ?
Where i can even call the invalid feedback ?
and also when button click it will check the valdiation first before call the database
As this code got some problem later in the end where i couldnt validate anything when button click as it passes to the database immediately without the validation check .
(function validateForm() {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.stopPropagation();
event.preventDefault();
}
form.classList.add('was-validated');
}, false)
})
})();
<form id="form" class="needs-validation" onsubmit="return validateForm()">
<!-- <label id="mandatoryField" class="hiddenfield" hidden>* is mandatory</label> -->
<div class="form-group row nameform">
<label for="validationName" class="col-form-label nameadduser">Name:</label>
<div class="col-6">
<input name="validationName" type="text" class="form-control" id="validationName" placeholder="Name" title="Name can be any. e.g. john" required>
<div class="invalid-feedback">
Enter a Name!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationEmail" class="col-form-label emailadduser">Email:</label>
<div class="col-6">
<input name="validationEmail" type="email" class="form-control emails" id="validationEmail" placeholder="example1#gmail.com" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<div style="margin-left: 3px;" class="invalid-feedback">
Enter a correct Email format!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationUserName" class="col-form-label usernameadduser">Username:</label>
<div class="col-6 ">
<input name="validationUserName" type="text" class="form-control " id="validationUserName" placeholder="Username" pattern="^(?=.{4,}$)(?:[a-zA-Z\d]+(?:[a-zA-Z\d])*)+$" title="Username should be at least 4 letter" required>
<div class="invalid-feedback">
Username must meet the following requirements:
<b>At least four letter</b>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label oldpasswordadduser">Old<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" type="password" class="form-control pass" id="oldpasswords" placeholder="Password" required>
<i class="bi bi-eye-slash" id="toggleoldPassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" title="Password should be like this. e.g. A123de!123"
required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onChange="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
<div style="margin-left: 20px;" class="invalid-tooltip">
Password do not match or value is null!
</div>
</div>
</div>
<div id="passwordconfirm"></div>
<div class="form-group row">
<label for="validationRole" class="col-form-label role">Role:</label>
<div class="col-3 ">
<select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
<option class="selectrole" selected disabled value="">Select ....</option>
</select>
<div style="margin-left: 10px;" class="invalid-feedback">
Enter a valid user role!
</div>
</div>
</div>
<div class="form-group row placeholderimage">
<img src="" id="output" width="400" height="400" style="border-radius: 50%;" />
<input id="file-upload-input" type="file" accept="image/*" onchange="encodeImageFileAsURL(event);">
</div>
<button id="submitbtn" type="submit" class="btn-primary submitbutton" disabled>Done</button>
</form>
I have a button onclick where i got my database out when click which is this code it is with sweetalert as well not sure do we need to put the prevent button for validation here ?
$('#submitbtn').click(function() {
//get input value field
var name = $('#validationName').val();
var email = $('#validationEmail').val();
var username = $('#validationUserName').val();
var oldpassword = $('#oldpasswords').val();
var password = $('#passwords').val();
var picture = document.getElementById("output").src;
var role = $('#select-user-role').val();
//making ajax call after this retrieve
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/postWithRawBody",
method: "POST",
contentType: "text/plain;charset=UTF-8",
headers: {
// Generally used for queries that we're planning to use
query: `UserUpdate(,'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','','${formatParamString(password)}','','${formatParamString(role)}')`,
// apikey like oXkPNt3p6cuDobzBVjpsPUyawSYDFqFHVWPkijXZZstjVPLLWo
"Content-Type": "text/plain",
apikey: sessionStorage.getItem("apikey")
},
dataType: "text",
// May be quite long
// Usually an array
// Only for specific conditions
data: `UserUpdate(${getQueryInfo()["id"]},'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','${formatParamString(oldpassword)}','${formatParamString(password)}','${formatParamString(picture)}','${formatParamString(role)}')`,
success: function(data, textStatus, xhr) {
// showing response from API
// showing response box that is added
//console.log(data)
$('#response').html("<div class='alert alert-success'>" + "<b>Success!</b> The information have been updated <b>successfully</b>" + "</div>")
Swal.fire({
icon: 'success',
title: 'Update Successfully!',
html: 'The information have been updated successfully!<br>By pressing <b>okay</b> this page will go to <b>view users</b> page',
showCancelButton: true,
cancelButtonText: "Cancel",
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonText: 'Okay',
cancelButtonColor: '#9b3be7', // purple
confirmButtonColor: '#79b446', // light green
heightAuto: false,
})
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
.then(function(inputvalue) {
if (inputvalue.isConfirmed) {
window.location.assign('viewUsers.html?id=' + getQueryInfo()['id'])
} else if (inputvalue.isCancel) {
Swal.fire('')
}
})
},
error: function(xhr, textStatus, err) {
if (xhr["status"] == 409) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> There is an <b>duplicate</b> on username!" + "</div>")
//then
// setTimeout(function(){ window.location.reload(); },5000); //reload a page after 5 seconds
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'There is an <label class="color-text"><b>duplicate</b></label> on username!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>username</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
if (xhr["status"] == 400) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> The <b>old password </b> is incorrect!" + "</div>")
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'The <label class="color-text"><b>old password</b></label> is incorrect!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>old password</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
// if (xhr["status"] == "(failed)") {
// $('#response').html("<div class='alert alert-danger'>"+"<b>Error!</b> There is an <b>duplicate</b> on username! where you cant add in image"+"</div>")
// }
}
});
})
I cannot get the jQuery plugin to validate minlength and maxlength. I cannot see the error message that the minimum length or maximum length as I specify. The contact form and the jQuery code of the contact form are as follows:
The contact form:
<form id="contactForm" class="contact-form" action="form.php" method="POST">
<div class="contact-form-success alert alert-success d-none mt-4" id="contactSuccess">
<strong>Success!</strong> Message sent!.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4" id="contactError">
<strong>Error!</strong> There was an error.
<span class="mail-error-message text-1 d-block" id="mailErrorMessage"></span>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Name</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
</div>
<div class="form-row">
<div class="form-group col">
<label class="font-weight-bold text-dark">Phone</label>
<input type="text" value="" data-msg-required="Please enter your phone number." maxlength="100" class="form-control" name="subject" id="subject" required>
</div>
</div>
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Email</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<input type="submit" value="Send Message" class="btn btn-primary btn-modern" data-loading-text="Loading...">
</div>
</div>
</form>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/additional-methods.js"></script>
Jquery and Javascripts links:
<script>
jQuery(function ($) {
$("#contactForm").validate({
errorClass: "error fail-alert",
validClass: "valid success-alert",
rules: {
name : {
required: true,
minlength: 3
},
phone: {
required: true,
number: true,
minlength: 8
},
email: {
required: true,
email: true
},
}
});
});
</script>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
Validation works, but minimum and maximum length are not working, and the error messages do not capture that; alternatively, it gives me a green tick (i.e., validated). I am not sure what is the reason for that.
My code is executing only else statement ... I couldn't find a problem.
When I validated form attribute address with javascript, it is not taking validation from PHP code and taking else statement
expected result: Thanks for your order
actual result: technical issue
<?php
$toEmail = "herbsoul1#gmail.com";
$mailHeaders = "From: " . $_POST["name"] . "<". $_POST["email"] .">\r\n";
$subject="Site Mail from Xtreme-Fatburn";
$content="Name : ".$_POST["name"]."\n";
$content=$content."MobileNo : ".$_POST["MobileNo"]."\n";
$content=$content."Email : ".$_POST["email"]."\n";
$content=$content."State : ".$_POST["State"]."\n";
$content=$content."Address : ".$_POST["address"]."\n";
if(mail($toEmail, $subject, $content, $mailHeaders)) {
print "Thanks for your order.";
} else {
print "Some Technical Issues occured.";
}
?>
background code
<div id="about1" class="container-fluid " style="width:100%;height:580px">
<div class="row bg">
<div class="col-md-9"></div>
<div class="col-md-2" style="margin-top:192px;margin-left:0px;">
<div class="row main">
<div class="main-login main-center">
<form class="form-horizontal" method="post">
<div class="form-group">
<label for="name" class="cols-sm-2 control-label dntr">Your Name</label><span id="userName-info" class="info">*</span>
<div class="cols-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="name" id="name" maxlength="30" placeholder="Enter your Name" />
</div>
</div>
</div>
<div class="form-group">
<label for="username" class="cols-sm-2 control-label dntr">Mobile No</label><span id="userName-info" class="info">*</span>
<div class="cols-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-mobile-phone" style="font-size:20px"></i></span>
<input type="text" class="form-control" name="MobileNo" id="MobileNo" onkeypress="return isNumber(event)" maxlength="10" placeholder="Enter your Mobile No" />
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="cols-sm-2 control-label dntr">Your Email ID</label><span id="userName-info" class="info"></span>
<div class="cols-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" maxlength="30" name="email" id="email" placeholder="Enter your Email ID" />
</div>
</div>
</div>
<div class="form-group">
<label for="username" class="cols-sm-2 control-label dntr">State</label><span id="userName-info" class="info">*</span>
<div class="cols-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
<select class="form-control" id="sel1">
<option>Andaman and Nicobar Islands</option>
<option>Andhra Pradesh</option>
<option>Arunachal Prades</option>
<option>Assam</option>
<option>Bihar</option>
<option>Chhattisgarh</option>
<option>Chandigarh</option>
<option>Dadra and Nagar Haveli</option>
<option>Daman and Diu</option>
<option selected>Delhi</option>
<option>Goa</option>
<option>Gujarat</option>
<option>Haryana</option>
<option>Himachal Pradesh</option>
<option>Jammu and Kashmir</option>
<option>Jharkhand</option>
<option>Karnataka</option>
<option>Kerala</option>
<option>Lakshadweep</option>
<option>Madhya Pradesh</option>
<option>Maharashtra</option>
<option>Manipur</option>
<option>Meghalaya</option>
<option>Mizoram</option>
<option>Nagaland</option>
<option>Odisha</option>
<option>Punjab</option>
<option>Puducherry</option>
<option>Rajasthan</option>
<option>Sikkim</option>
<option>Tamil Nadu</option>
<option>Telangana</option>
<option>Tripura</option>
<option>Uttarakhand</option>
<option>Uttar Pradesh</option>
<option>West Bengal</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="address" class="cols-sm-2 control-label dntr">Your Address</label><span id="userName-info" class="info">*</span>
<div class="cols-sm-6">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="address" id="address" maxlength="30" placeholder="Enter your address" />
</div>
</div>
</div>
<div class="form-group" style="padding-top:10px;">
<button type="button" class="btn btn-primary btn-lg btn-block login-button" id="Register" onClick="sendContact();">RUSH MY ORDER</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>
</div>
javascript code
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<style>
.info {
font-size: .8em;
color: #FF6600;
letter-spacing: 1px;
padding-left: 5px;
}
</style>
<script>
function sendContact() {
var valid;
valid = validateContact();
if (valid) {
var name1 = $("#name").val();
var MobileNo1 = $("#MobileNo").val();
var email1 = $("#email").val();
var state1 = $("#sel1").val();
var address1 = $("#address").val();
jQuery.ajax({
url: "sendemail.php",
data: {
name: name1,
MobileNo: MobileNo1,
email: email1,
State: state1,
address: address1
},
type: "POST",
success: function(data) {
//$('#Register').html(data);
$("#name").val('');
$("#MobileNo").val('');
$("#email").val('');
$("#address").val('');
//$("#mail-status").html(data);
alert(data);
},
error: function() {}
});
}
}
function validateContact() {
var valid = true;
if (!$("#name").val()) {
valid = false;
alert("Please Enter Your Name");
return valid;
}
if ($("#email").val()) {
if (!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
valid = false;
alert("Invalid Email ID");
return valid;
}
}
if (!$("#MobileNo").val()) {
valid = false;
alert("Please Enter Your Mobile Number");
return valid;
}
return valid;
}
$(document).ready(function() {
$('.openPopup').on('click', function() {
debugger;
$(".modal-content").html('');
var dataURL = $(this).attr('href');
//$('.modal-body').load(dataURL,function(){
// $('#dialog-example').modal({show:true});
//});
$.get(dataURL, function(data) {
//alert(data);
$(".modal-content").html(data).foundation("open");
});
});
});
function isNumber(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 46 && charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
For getting the post data, change the button type to submit:
type="submit"
Also check the post data before sending mail
If you are working locally in windows In C:\xampp\php in php.ini file you have to check the setup. Find mail function and do the changes as below
[mail function]
; XAMPP: Don’t remove the semi column if you want to work with an SMTP Server like Mercury
; SMTP = localhost
; smtp_port = 25
Remove the semi colons before SMTP and smtp_port and set the SMTP to your smtp server and the port to your smtp port. Your settings should look as follows
SMTP = smtp.example.com
smtp_port = 25
And if your configuration is fine, please check the mail spam folder or mail configuration, whether it has some restriction.
OR
Use PHPMailerAutoload.php PHPMailer, that is quiet easy.
I tried your "HTML, Javascript & PHP" codes in my Windows XAMPP and after configuring the details in the php.ini & in sendmail.ini files, as given in this link, I can successfully send the email.
I have the following 'contact me' form (in a partial) in OctoberCMS
<form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="g-recaptcha" id="gcaptcha" data-sitekey="sitekeydataCjaelksjEJlakch"></div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
When the user clicks submit - it's handled via javascript (which is what helps with input validation). I'm using JQuery.
The JS looks like this:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var gcaptcha = $("#gcaptcha").data('sitekey');
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message,
gcaptcha: gcaptcha
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
The contact_me.php form looks like this:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$secret = "alkfejasupersecretkeyalkjeociyseh13987fa9s8df7";
$gcaptcha = $_POST['gcaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$gcaptcha."&remoteip=".$remoteip;
$result = json_decode($url, true);
var_dump($result);
/*
if ($result['success'] == 1) {
//do mail here
}
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
*/
?>
As you can see - I'm trying to just see if I'm even getting to the contact_me.php form which it doesn't appear I am. Before I had commented it out - the mail never sent - which is why I started playing around trying to see if my data is even hitting the contact_me.php page. I see the success message when submitting - but the data never goes anywhere and no email is ever had.
I can see in Firebug that the data is posting to contact_me - but I can't tell much beyond that. The var_dump doesn't work and I'm in need of further assistance to either better troubleshoot this issue or figure out what isn't working.
After a lot of help from Xorifelse in the comments I realized that the code was probably fine (or at least suitable).
I ended up going a different direction. I updated the form a bit so it looks like this:
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Contact Me</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<form name="sentMessage" id="contactForm" data-request="onSend" data-request-success="alert('We have received your email. Thank you!'); this.reset();" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input name="name" type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input name="email" type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input name="phone" type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea name="contact-msg" rows="5" class="form-control" placeholder="Message" id="contact-msg" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="g-recaptcha" id="sitekey" data-sitekey="gcaptchasitekey3897vadf834fadf"></div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
Note the 'onSend' data-request parameter.
In the default layout - I put this snippet of PHP to handle the actual processing (the onSend function):
function onSend()
{
if(empty(post('name')) ||
empty(post('email')) ||
empty(post('phone')) ||
empty(post('contact-msg')) ||
empty(post('g-recaptcha-response')) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "Please fill out all required fields.";
return false;
}
// Collect input
$name = post('name');
$email = post('email');
$phone = post('phone');
$body = post('contact-msg');
$response = post('g-recaptcha-response');
$remoteip = $_SERVER['REMOTE_ADDR'];
$secret = "32supersecretkeyackjaBcjeLCJelahd832CDo";
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip);
$response = json_decode($url, true);
// Form Validation
$validator = Validator::make(
[
'name' => $name,
'email' => $email,
'phone' => $phone,
'contact-msg' => $body,
],
[
'name' => 'required',
'email' => 'required|email',
'contact-msg' => 'required',
]
);
if ($validator->fails())
{
$messages = $validator->messages();
throw new ApplicationException($messages->first());
}
// Make sure the captcha is verified before sending
if (isset($response['success'])&&$response['success']=="true"){
$to = config('mail.from.address');
$params = compact('name','email','phone','body');
Mail::sendTo($to, 'freelance::mail.contact', $params);
return true;
}
else {
return false;
}
}
I was able to trim down the JS file to this:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
So it provides active validation as the user is typing (which is great).
This method also required a little additional setup on the backend:
You need to create a new 'Mail Template' (code: freelance::mail.contact) in the Settings portion of the backend (and of course, make sure your mail settings are setup)
I would have liked to do a little more JS once the submission is successful - so maybe in the future I'll work that into it - but this is now working as intended.
I have written a code to pass values from a form using ajax but the values passed to another php page is not getting displayed there. I want to display the values passed in email.php file and send it as a mail to a email-id.
My script :
$(function() {
$('#send_message').on('click', function(e) {
var name = $('#exampleInputName1').val();
var email = $('#exampleInputEmail1').val();
var tel = $('#exampleInputTelephone1').val();
var cn = $('#exampleInputCountry1').val();
var message = $('#exampleInputMessage1').val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'php/email.php',
data: {
name: name,
email: email,
tel: tel,
cn: cn,
message: message
},
success: function(data) {
alert(message);
}
});
});
});
html page:
<form name="contactForm1" id='contact_form1' method="post" action='php/email.php'>
<div class="form-inline">
<div class="form-group col-sm-12 padd">
<input type="text" class="form-control" name="name" id="exampleInputName1" placeholder="name">
</div>
<div class="form-group col-sm-12 padd">
<input type="email" class="form-control" name="email" id="exampleInputEmail1" placeholder="email address">
</div>
<div class="form-group col-sm-12 padd">
<input type="text" class="form-control" name="telephone" id="exampleInputTelephone1" placeholder="phone">
</div>
<div class="form-group col-sm-12 padd">
<input type="text" class="form-control" name="Country" id="exampleInputCountry1" placeholder="Country">
</div>
<div class="form-group col-sm-12 padd">
<textarea class="form-control" name="message" rows="3" id="exampleInputMessage1" placeholder="message"></textarea>
</div>
</div>
<div class="form-group col-xs-12 padd">
<div id='mail_success' class='success' style="display:none;">Your message has been sent successfully.
</div>
<!-- success message -->
<div id='mail_fail' class='error' style="display:none;">Sorry, error occured this time sending your message.
</div>
<!-- error message -->
</div>
<div class="form-group col-xs-8 padd" id="recaptcha2"></div>
<div class="form-group col-sm-4 padd" id='submit'>
<input type="submit" id='send_message' name="sendus" class="btn btn-lg costom-btn" value="send">
</div>
</form>
email.php
<?php
$temp = $_POST['name'];
echo $temp;
?>
Can anyone suggest how to do this ?