Google Recaptcha with PHP mailer not working - javascript

So I am trying to use the recaptcha v2 where I have completed the client side part of putting the captcha but the another of server side validation gives an error where the form is submitted but the message shows that "Please click on the reCAPTCHA box." whereas the button is been clicked & also the mail part is not working. I know there is some issue with the JS code to take the POST value of recaptcha in PHP page but could not work on it.. Can anyone help me with it? I have Attached the HTML, JS & PHP code below....
HTML
<form class="comment-one__form contact-form-validated" novalidate="novalidate">
<div id="success" class="alert alert-success"></div>
<div class="row">
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="text" placeholder="Your name" name="name" id="name">
</div>
</div>
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="email" placeholder="Email address" name="email" id="email">
</div>
</div>
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="text" placeholder="Phone number" name="phone" id="phone">
</div>
</div>
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="text" placeholder="Subject" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="comment-form__input-box text-message-box">
<textarea name="message" id="message" placeholder="Write comment"></textarea>
</div>
<div class="comment-form__btn-box">
<div class="g-recaptcha" id="gcaptcha" data-sitekey="SITE KEY"></div>
<button type="submit" id="csubmit" class="thm-btn comment-form__btn">Send a
message</button>
</div>
</div>
</div>
</form>
JS
if ($(".contact-form-validated").length) {
$(".contact-form-validated").validate({
// initialize the plugin
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
digits: true,
minlength: 10,
maxlength: 10,
},
message: {
required: true
},
subject: {
required: true
}
},
messages: {
name: {
required: "Please enter your name",
},
email: {
required: "Please enter your email",
email: "Please enter vaild email",
},
phone: {
required: "Please enter your number",
digits: "Please enter only numbers",
minlength: "The phone number cannot be less than 10 digits",
maxlength: "The phone number cannot be more than 10 digits",
},
message: {
required: "Please enter your message",
},
},
submitHandler: function (form) {
// sending value with ajax request
$('#csubmit').html('Sending...');
var user_name = $("#name").val();
var user_email = $("#email").val();
var user_phone = $("#phone").val();
var user_subject = $("#subject").val();
var user_message = $("#message").val();
var gcaptcha = $(".g-recaptcha").val();
var formDatanew = new FormData();
formDatanew.append("name", user_name);
formDatanew.append("email", user_email);
formDatanew.append("phone", user_phone);
formDatanew.append("subject", user_subject);
formDatanew.append("message", user_message);
formDatanew.append("g-recaptcha-response", gcaptcha);
$.ajax({
url: 'vendor/process.php',
type: "POST",
data: formDatanew,
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false,
success: function (data) {
$("form").trigger("reset");
$('#csubmit').html('Send Message');
$('#success').fadeIn().html(data);
setTimeout(function(){
$('#success').fadeOut("Slow");
}, 5000);
}
});
return false;
}
});
}
PHP
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';
if(isset($_POST['name']))
{
$name = addslashes($_POST['name']);
$email= addslashes($_POST['email']);
$contact = addslashes($_POST['phone']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
// Your Google reCAPTCHA generated Secret Key here
$secret = 'SECRET KEY';
$serverError = '';
if( ini_get('allow_url_fopen') ) {
//reCAPTCHA - Using file_get_contents()
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
} else if( function_exists('curl_version') ) {
// reCAPTCHA - Using CURL
$fields = array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$verifyResponse = curl_init("https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verifyResponse, CURLOPT_RETURNTRANSFER, true);
curl_setopt($verifyResponse, CURLOPT_TIMEOUT, 15);
curl_setopt($verifyResponse, CURLOPT_POSTFIELDS, http_build_query($fields));
$responseData = json_decode(curl_exec($verifyResponse));
curl_close($verifyResponse);
} else {
$arrResult = array ('response'=>'error','errorMessage'=>'You need CURL or file_get_contents() activated in your server. Please contact your host to activate.');
$serverError = true;
}
if(empty($serverError)) {
if($responseData->success) {
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; /*SMTP server*/
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "*****"; /*Username*/
$mail->Password = "*****"; /**Password**/
$mail->isHTML(true);
$mail->FromName = $name;
$mail->addReplyTo($email, $name);
$mail->Body = $body;
$mail->From = $email;
$mail->Subject = "Contact Form";
$mail->AddAddress("abc#test.com");
if($mail->Send()){
echo "Thank you! We will get back to you soon.";
}
else{
echo "Oops! Something went wrong.";
}
} else {
echo "Robot verification failed, please try again";
}
}
} else {
echo "Please click on the reCAPTCHA box.";
}
}
?>

Related

stripe doesn't save the customer email and name in the dashboard

I am using Stripe to accept donations on my website and everything works great but it doesn't save the customer name and email however I am passing it in the billing_details. I think I need to pass it also on the server side,but it gives me this error (Undefined array key "email") when I used the post method '$email=$_POST['email'].. my question is how to pass the email to 'receipt_email' correctly.
\Stripe\Stripe::setApiKey('my secret key');
if(!isset($_SESSION['amount'])){
header("Location: donations.php");
}
$amount = $_SESSION['amount'];
$donation = $amount * 100;
$email = $_POST['email'];
$customer = \Stripe\Customer::create(array(
'email' => $email
));
$intent = \Stripe\PaymentIntent::create([
'amount' => $donation,
'currency' => 'usd',
// Verify your integration in this guide by including this parameter
'metadata' => ['integration_check' => 'accept_a_payment'],
'automatic_payment_methods' => ['enabled' => true],
'customer' => $customer->id,
'receipt_email' => $email,
]);
?>
<!DOCTYPE html >
<html >
<head>
<body>
<form id="payment-form" data-secret="<?= $intent->client_secret ?>">
<label>Card Holder Name</label>
<span id="card-holder-name-info" class="info"></span><br>
<input type="text" id="fullname" name="fullname" required><br>
<label>Email</label>
<span id="email-info" class="info"></span><br>
<input type="email" id="email" name="email" required><br>
<label>Card Number</label>
<div id="card-element" >
<!-- Elements will create input elements here -->
</div>
<button type="submit" id="card-button" class="donate-btn yellow-btn">Donate</button>
</form>
</div>
</div>
<script>
var stripe = Stripe('my public key');
var elements = stripe.elements();
var style = {
base: {
color: "#565556",
}
};
var card = elements.create("card", { style: style });
card.mount("#card-element");
card.on('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
var form = document.getElementById('payment-form');
var fullname = document.getElementById('fullname');
var email = document.getElementById('email');
form.addEventListener('submit', function(ev) {
ev.preventDefault();
stripe.confirmCardPayment(form.dataset.secret, {
payment_method: {
card: card,
billing_details: {
name: fullname,
email: email
}
}
}).then(function(result) {
if (result.error) {
// Show error to your customer (e.g., insufficient funds)
alert(result.error.message);
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
// Show a success message to your customer
alert('The payment has been proccessed');
window.location.replace("SuccessPage");
}
}
});
});
</script>

How to make it mandatory to check the form's checkbox?

I have a form configured with PHP and I'm lost, I do not know how to make it mandatory to check the checkbox that I put in the terms and conditions. I have put the ID but I do not know how to put it in the PHP file. I do not know if I should add something to the javascript file. I show you the three files so they can tell me how to correct the errors, rather I should add to the PHP file.
I have added the PHP code along with the Javascript since I do not know how to add it in any other way.
The form when I give to send shows me the following:
There was an error sending the form. Please try again later
I have several errors in the console when sending the form:
POST https://agrochema.000webhostapp.com/includes/contact.php net::ERR_NAME_NOT_RESOLVED
send # jquery-1.12.4.js:17
ajax # jquery-1.12.4.js:17
(anonymous) # form-script.js:21
dispatch # jquery-1.12.4.js:16
r.handle # jquery-1.12.4.js:16
-- XHR failed loading: POST "https://agrochema.000webhostapp.com/includes/contact.php"
s
end # jquery-1.12.4.js:17
ajax # jquery-1.12.4.js:17
(anonymous) # form-script.js:21
dispatch # jquery-1.12.4.js:16
r.handle # jquery-1.12.4.js:16
Thank you
// Archivo PHP
<?php
//require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'tls://smtp.gmail.com:587'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'Password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$message = "";
$status = "false";
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['form_name'] != '' AND $_POST['form_email'] != '' ) {
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_message'];
$botcheck = $_POST['form_botcheck'];
$toemail = 'miguelestabaenlaparra#gmail.com'; // Your Email Address
$toname = 'Unlock Design'; // Your Name
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = $name.' '.$email.' '.$message.' '.$referrer;
$mail->MsgHTML( $body );
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
));
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$responseArray = array('type' => 'success', 'message' => $okMessage);
else:
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
endif;
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
//$status_array = array( 'message' => $message, 'status' => $status);
//echo json_encode($status_array);
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['message'];
}
?>
// ARCHIVO JAVASCRIPT
// CONTACT FORM 2 SCRIPT
// ===========================
$(function () {
$('#contact_form2').validator();
$('#contact_form2').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "includes/contact2.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_form2').find('.messages').html(alertBox).fadeIn('slow');
$('#contact_form2')[0].reset();
setTimeout(function(){ $('.messages').fadeOut('slow') }, 6000);
}
}
});
return false;
}
})
});
<DOCTYPE html>
<body>
<section class="ulockd-contact-page">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="ulockd-contact-form ulockd-style-two">
<form id="contact_form" name="contact_form" class="contact-form" action="includes/contact.php" method="post"
novalidate="novalidate">
<div class="messages"></div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="form_name" name="form_name" class="form-control ulockd-form-fg required" placeholder="Nombre"
required="required" data-error="Nombre requerido." type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_email" name="form_email" class="form-control ulockd-form-fg required email"
placeholder="Email" required="required" data-error="Email requerido." type="email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_phone" name="form_phone" class="form-control ulockd-form-fg required" placeholder="Teléfono"
required="required" data-error="Numero de telefono requerido." type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input id="form_subject" name="form_subject" class="form-control ulockd-form-fg required"
placeholder="Tema" required="required" data-error="Tema requerido." type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea id="form_message" name="form_message" class="form-control ulockd-form-tb required" rows="8"
placeholder="Su mensaje" required="required" data-error="Mensaje requerido."></textarea>
<div class="help-block with-errors"></div>
</div>
<input type="checkbox" name="aceptar_terminos" id="aceptar_terminos" value="aceptar_terminos" /> He leído y acepto los terminos y condiciones
<div class="form-group ulockd-contact-btn">
<input id="form_botcheck" name="form_botcheck" class="form-control" value="" type="hidden">
<button type="submit" class="btn btn-default btn-lg ulockd-btn-thm" data-loading-text="Getting Few Sec...">ENVIAR</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
First make your field required (required="required") on HTML form for JS validation:
<input
type="checkbox"
name="aceptar_terminos"
id="aceptar_terminos"
value="aceptar_terminos"
required="required"
/>
As you are using serialize() the checkbox values will only send it if its checked, then you can validate on your PHP as well. Like:
if(
!empty($_POST['form_name']) AND
!empty($_POST['form_email']) AND
!empty($_POST['aceptar_terminos']) AND
$_POST['aceptar_terminos'] == 'aceptar_terminos'
) { ... }
Also update your PHP to only require the files and call the class if the form is valid:
<?php
$message = "";
$status = "false";
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if(
!empty($_POST['form_name']) AND
!empty($_POST['form_email']) AND
!empty($_POST['aceptar_terminos']) AND
$_POST['aceptar_terminos'] == 'aceptar_terminos'
) {
//require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'tls://smtp.gmail.com:587'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'Password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_message'];
$botcheck = $_POST['form_botcheck'];
$toemail = 'miguelestabaenlaparra#gmail.com'; // Your Email Address
$toname = 'Unlock Design'; // Your Name
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
$mail->AddAddress( $toemail , $toname );
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = $name.' '.$email.' '.$message.' '.$referrer;
$mail->MsgHTML( $body );
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
));
$sendEmail = $mail->Send();
if( $sendEmail == true ):
$responseArray = array('type' => 'success', 'message' => $okMessage);
else:
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
endif;
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
} else {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
//$status_array = array( 'message' => $message, 'status' => $status);
//echo json_encode($status_array);
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['message'];
}
?>

Why does my submit button gets re-enabled before all fields are filled in?

I'm using the code below to validate (through bootstrap-validator) the content of each field in my contact form (there's also an extra check via google recaptcha). You can see and test the form at at this address.
By default, the submit button is disabled <button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> SEND</button>, and is supposed to be re-enabled once all the fields are validated via bootstrap-validator and google recaptcha completed.
Issue: the submit button gets re-enabled directly once the first field is filled-in so there must be something somewhere that reactivates it (you can do a test by typing your name in the first field and then put your mouse over the submit button, and you will see that the button is active instead of disabled)
Any idea what the issue is and how to fix this?
Many thanks
JS:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
feedbackIcons: {
valid: 'fa fa-check',
invalid: 'fa fa-times',
validating: 'fa fa-refresh'
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'aaVeuillez indiquer votre prénom'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'aaVeuillez indiquer votre nom'
}
}
},
email: {
validators: {
notEmpty: {
message: 'aaVeuillez indiquer votre adresse e-mail'
},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'aaVeuillez indiquer une adresse e-mail valide'
}
}
},
message: {
validators: {
stringLength: {
min: 20,
max: 1000,
message:'aaVotre message doit faire plus de 20 caractères et moins de 1000.'
},
notEmpty: {
message: 'aaVeuillez indiquer votre message'
}
}
}
}}).on('success.form.bv', function (e) {
e.preventDefault();
$('button[name="submit"]').hide();
var bv = $(this).data('bootstrapValidator');
// Use Ajax to submit form data
$.post($(this).attr('action'), $(this).serialize(), function (result) {
if (result.status == 1) {
$('#error_message').hide();
$('.g-recaptcha').hide();
$('#success_message').slideDown({
opacity: "show"
}, "slow");
$('#contact_form').data('bootstrapValidator').resetForm()
} else {
$('button[name="submit"]').show();
$('#error_message').slideDown({
opacity: "show"
}, "slow")
}
}, 'json');
}
);
});
Submit btn:
<button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> ENVOYER</button>
Additional script on the contact page:
<script type="text/javascript">
function recaptcha_callback(){
$('#submit-btn').removeAttr('disabled');
}
</script>
my sendmessage.php:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$email_vars = array(
'message' => str_replace("\r\n", '<br />', $_POST['message']),
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'organisation' => $_POST['organisation'],
'server' => $_SERVER['HTTP_REFERER'],
'agent' => $_SERVER ['HTTP_USER_AGENT'],
);
// CAPTCHA
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '6LtQ6_y',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
// RE-VALIDATION (first level done via bootsrap validator js)
function died($error) {
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['message'])) {
died('*** Fields not filled-in ***');
}
//Enable SMTP debugging.
$mail->SMTPDebug = false;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "fdsfs";
$mail->Password = "#pz7HQ";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];
//To be anti-spam compliant
/* $mail->From = $_POST['email']; */
$mail->From = ('ghdsfds#gmail.com');
$mail->addReplyTo($_POST['email']);
$mail->addAddress("ghdsfds#outlook.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");
$mail->isHTML(true);
$mail->Subject = "Nouveau message depuis XYZ";
$body = file_get_contents('emailtemplate.phtml');
if(isset($email_vars)){
foreach($email_vars as $k=>$v){
$body = str_replace('{'.strtoupper($k).'}', $v, $body);
}
}
$mail->MsgHTML($body);
$response = array();
if(isValid()) {
// send mail
if(!$mail->send()) {
$response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
$response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
} else {
// handle error
$response = array('message' => 'Captcha was not valid');
}
/* send content type header */
header('Content-Type: application/json');
/* send response as json */
echo json_encode($response);
?>
Actually your code is working as expected and no error in your code. But in bootstrapValidator you need to check the status of every field before success.form.bv event, like describe below.
Please add this event before .success.form.bv event like describe below.
.on('status.field.bv', function(e, data) {
var $this = $(this);
var formIsValid = true;
$('.form-group', $this).each(function() {
formIsValid = formIsValid && $(this).hasClass('has-success');
});
$('#submit-btn', $this).attr('disabled', !formIsValid);
}).on('success.form.bv', function(e, data) {
Let me know if it not works.
Below is a pseudo code, kinda clone of the page that you shared, with the basic validation checks that are triggered on multiple events (keyup, change, keypress, blur).
It checks if all fields are filled or not, if any one is empty, button won't be enabled.
It checks if the input fields have minimum 2 characters.
It checks if the message field has message length between 20 to 1000.
And in the same manner, we can keep adding custom validations to our needs.
required = function(fields) {
console.clear();
var valid = true;
fields.each(function() { // iterate all
var $this = $(this);
if ((($this.is(':text') || $this.is('textarea')) && !$this.val())) {
valid = false;
}
if ($this.is(":text") && $this.val().length < 3) {
console.log('less than 2 characters..');
valid = false;
}
if ($(this).attr('id') == 'your_message' && ($this.val().length < 20 || $this.val().length > 1000)) {
console.log('aaVotre message doit faire plus de 20 caractères et moins de 1000.');
valid = false;
}
});
return valid;
}
validateRealTime = function() {
var fields = $("form :input");
fields.on('keyup change keypress blur', function() {
if (required(fields)) {
{
$("#register").prop('disabled', false);
}
} else {
{
$("#register").prop('disabled', true);
}
}
});
}
validateRealTime();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name<br />
<input type="text" id="user_input" name="firstname" /><br /> Name
<br />
<input type="name" id="name_input" name="name" /><br /> Email<br />
<input type="email" id="email_input" name="email" /><br />
<br/> Your Message
<textarea name="your_message" id="your_message"></textarea>
<br>
<input type="submit" id="register" value="Submit" disabled="disabled" />
</form>
Hope this helps you. Happy Coding!
There seems to be a problem with naming the submit button submit http://bootstrapvalidator.votintsev.ru/getting-started/#name-conflict It might have caused the unexpected behavior
Just write a separated validation to your form
$("#contact_form").on('change', function () {
$("form").each(function(){
if ($(this).find(':input').val()== "")
$('#submit-btn').addClass('disabled');
});
})

How to validate a form

I do have a html form which takes username and password as input . On button click , wrote a js function which would hit the api asynchronously . Before that , how would i validate it
<form>
<div><label id="resultString"></label></div>
<fieldset>
<legend>Login</legend>
Username: <input type="text" id="username"><br><br>
Password: <input type="password" id="password"><br><br>
<input type="button" onclick="submitdetails();" value="Login">
</fieldset>
</form>
My js function is :
function submitdetails() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var params = JSON.stringify({ username: username, password: password });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200)
document.getElementById("resultString").innerHTML = xmlhttp.responseText;
else
document.getElementById("resultString").innerHTML = "Error";
}
};
xmlhttp.open("POST","http://127.0.0.1:8000/login/",true);
xmlhttp.send(params);
}
<form id='form' name='form' method='post' action=''>
<div><label id="resultString"></label></div>
<fieldset>
<legend>Login</legend>
Username: <input type="text" id="username" name="username"><br><br>
Password: <input type="password" id="password" name="password"><br><br>
<input type="button" value="Login">
</fieldset>
</form>
And this is the validator plugin code:
$(document).ready(function() {
$('#form').validate({
rules: {
username: {
required: true
},
password: {
required: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
success: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
}
});
});
refer: https://jqueryvalidation.org/
DEMO
THINGS TO REMEMBER
Your form should have a name and id
I say, give name and id for all fields as well
Use submit handler to do the call you did on onclick
<script>
function submitdetails() {
var username = $("#username").val();
var password = $("#passwords").val();
if(username==""||password=="")
{
alert("please fill");
}
var params = JSON.stringify({ username: username, password: password });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200)
document.getElementById("resultString").innerHTML = xmlhttp.responseText;
else
document.getElementById("resultString").innerHTML = "Error";
}
};
xmlhttp.open("POST","http://127.0.0.1:8000/login/",true);
xmlhttp.send(params);
}
using following conditions
if(username ==null || username =="")
{
document.getEelementById("showerr").innerHTML = "is empty";
}
if(password==null || password =="" password.length < 6)
{
document.getEelementById("showerr").innerHTML = "must 6 or above characters";
}
HTML :
<span id="showerr"></span>
using regular expression you can validate
http://jsfiddle.net/ghvj4gy9/embedded/result,js/
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["email"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<br/>
email: <input type="text" name="email">
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
But its easy to use use jQuery validate plugin
Demo : https://jqueryvalidation.org/files/demo/
Documentation : https://jqueryvalidation.org/documentation/
sample code -
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});

Cannot get jquery.multiple.select.js to validate and pass to php the boxes checked

I am using jquery.multiple.select.js v1.1.0 and cannot get this to validate and pass the output to my php mailer. My objective is for the visitor to my site to select from multiple options requesting a quote. So far, I'm able to receive the email with all other fields validated but in the email, I receive"quote for: array" but no selections. Also related, I'm not getting the success or error message on the page even though the email is going out. Can anyone steer me in the right direction? I'll include the page in question here, http://cptest.info/h2contact375.html
here's the validation js
var Contact = {
initialized: false,
initialize: function() {
if (this.initialized) return;
this.initialized = true;
this.build();
this.events();
},
build: function() {
this.validations();
},
events: function() {
},
validations: function() {
$("#contactForm").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "js/contact-form.php",
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"telephone": $("#contactForm #telephone").val(),
"message": $("#contactForm #message").val(),
"ms": $("#contactForm #ms").val()
},
dataType: "json",
success: function (data) {
if (data.response == "success") {
$("#contactSuccess").removeClass("hidden");
$("#contactError").addClass("hidden");
$("#contactForm #name, #contactForm #email, #contactForm #telephone, #contactForm #message, #contactForm #ms")
.val("")
.blur()
.closest(".control-group")
.removeClass("success")
.removeClass("error");
if(($("#contactSuccess").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactSuccess").offset().top - 80
}, 300);
}
} else {
$("#contactError").removeClass("hidden");
$("#contactSuccess").addClass("hidden");
if(($("#contactError").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactError").offset().top - 80
}, 300);
}
}
}
});
},
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
telephone: {
required: true
},
message: {
required: true
},
ms:{
required: true,
message: 'Please select at least one'
},
},
highlight: function (element) {
$(element)
.closest(".control-group")
.removeClass("success")
.addClass("error");
},
success: function (element) {
$(element)
.closest(".control-group")
.removeClass("error")
.addClass("success");
}
});
}
};
Contact.initialize();
here's the php
<?php
// check if fields passed are empty
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message'])||
empty($_POST['telephone'])||
empty($_POST['ms']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!"; return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$ms = $_POST['ms'];
// create email body and send it
$to = "myemail#gmail.com";
// put your email
$email_subject = "Contact form submitted by: $name"; $email_body = "You have received a new message. \n\n".
" Here are the details:\n \nName: $name \n ".
"Telephone: $telephone \n" .
"Quote For: $ms \n" .
"Email: $email_address\n Message: \n $message";
//$headers = "From: me#youremail.com\n";
//$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers); return true;
?>
give name to your field called ms otherwise it will not go to php because it identifies name not id and based on your condition checking it will always show No arguments Provided!.
<select id="ms" multiple="multiple" name="ms">
Try Using $_REQUEST in your PHP if $_POST is not providing the data to check.
NOTE: there is no styling added just expect it to send data to your php nothing else.
<?php
// check if fields passed are empty
print_r($_REQUEST);//it should display the send data
//rest of the code with request
DEMO
You can use the following code to validate so validation plugin will not ignore the hidden <select> element.
The magic happens in this line:
ignore: ':hidden:not("#ms")',
add it to validation script
//AjaxCall Code
},
ignore: ':hidden:not("#ms")',
rules: {
//Rules and messages onwards
Above will fix the issue of validation,
And about data not posting, there is no name="" in <select> tag so add it one, and after validation, <select> value will be posted along with other inputs in <form>
<select style="display: none;" name="ms" id="ms" multiple="multiple" >

Categories

Resources