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>
Related
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.";
}
}
?>
The client-side validation in ASP.Net Core is not working. I have the following code:
#model VeoScheduling.Models.SignInModel
#{
ViewData["Title"] = "SignIn";
}
<div class="login">
<h2>Sign In</h2>
<div>
<form method="post" asp-action="SignIn">
<input type="hidden" asp-for="RedirectUrl" />
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input type="email"
data-bind="value: email" asp-for="Email"
class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"
class="control-label"></label>
<input type="password" asp-for="Password"
data-bind="value: password"
class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Account</label>
<select name="accountSelected" style="margin:5px;width:200px"
data-bind='options: availableAccounts, optionsText: "value", optionsValue: "key", value: selectedAccount,event:{change: accountSelected()}'></select>
</div>
<br />
#if (Model.Error != "" || Model.Error != null)
{
<p style="color:red">#Html.Raw(Model.Error)</p>
}
</form>
</div>
</div>
#section Scripts{
<script>
var vModel = #Html.Raw(Json.Serialize(Model))
</script>
<script src="~/js/signIn.js" asp-append-version="true"></script>
}
I have also added javascript validation files and I can see they are being loaded when I run but still client-side validation is not working.
I have applied required attribute for both email and password filed. But client-side validation is still not working.
public class SignInModel
{
[Required(ErrorMessage ="Email is required")]
public string Email { get; set; }
[Required(ErrorMessage ="Password is required")]
public string Password { get; set; }
[DisplayName("Forgot Password")]
public bool ForgotPassword { get; set; }
public string RedirectUrl { get; set; }
public string Error { get; set; }
}
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
Below is the js code.
var viewModel = function (model) {
var self = this;
//properties
self.email = ko.observable('');
self.password = ko.observable('');
self.redirectUrl = model.redirectUrl;
self.availableAccounts = ko.observableArray(model.availableAccounts);
self.selectedAccount = ko.observable(null);
//events
self.signOn = function () {
var payloadData = {
'email': self.email(),
'password': self.password(),
'accountSelected': self.selectedAccount()
};
var url = window.location.origin + '/account/SignIn';
CallService("Post", url, payloadData)
.done(function (data) {
var url = window.location.origin + self.redirectUrl;
window.location.replace(url);
});
};
self.accountSelected = function (e, d) {
//alert(self.selectedStack());
};
//methods
self.forgotPassword = ko.observable(false);
self.resetPassword = function () {
$('#loader').show();
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/resetPassword'
$.post(url, payloadData)
.always(function () {
$('#loader').hide();
})
.fail(function (xhr, status, error) {
alert('resetPassword(): error' + xhr.responseText);
})
.done(function (data) {
alert("reset email sent.");
});
};
//ajax
self.getUsersAccounts = function () {
if (self.email() === "")
return;
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/GetAccountsByEmail';
CallService("GET", url, payloadData)
.done(function (data) {
self.availableAccounts.removeAll();
self.availableAccounts(data);
});
};
//computed
self.userChanged = ko.computed(function () {
var userID = self.email();
//alert(userID);
//console.log(userID);
self.getUsersAccounts();
});
self.forgotChecked = ko.computed(function () {
var checked = self.forgotPassword();
var email = self.email();
if (checked) {
if (email === '') {
alert("Please fill in email to reset password");
self.forgotPassword(false);
}
else {
alert("An email link will be sent to your email address.");
self.resetPassword();
self.forgotPassword(false);
}
}
});
//init
if (model.availableAccounts.length === 1) {
self.selectedAccount(model.availableAccounts[0].key);
}
};
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
you could try:
<form id="someform">
......
</form>
<script>
.....
if ($("#someform").valid())
{
//ajax codes
}
else {
return false;
}
</script>
also you could try:
var somevalue = document.getElementById("someId").value;
if (somevalue == null || somevalue == '')
{
$('#somespanId').html("*required");
return false;
}
I have a custom HTML form with a stripe card input element to checkout. I can't seem to find a way to pass the shipping info retrieved from the form to the payment invoice on the stripe dashboard.
My HTML code:
<form action="admin/charge.php" method="post" id="payment-form">
<div class="form-row">
<input type="hidden" name="total" value="<?= $stripe_total?>"> </input>
<input name = "first" type="text" placeholder="First Name*" required maxlength="20" id="first">
<input name = "last" type="text" placeholder="Last Name*" required maxlength="20" id="last">
<input type="email" name="email" placeholder="Email Address*" id="email" maxlength="30" required>
<input type="tel" name="phone" id="phone" placeholder="Phone" maxlength="10">
<input name = "addy1" type="text" placeholder="Address Street Name*" required maxlength="35" id="addy1">
<input name = "addy2" type="text" placeholder="Address 2" maxlength="15" id="addy2">
<input type="text" name="zip" id="zip" placeholder="Zip Code*" required maxlength="11">
<input type="text" name="city" id="city" placeholder="City*" required maxlength="20">
<select name="state" id="state">
<option value="State">State</option>
//every state
</select>
<select required name="country" id="country">
<option value='Countries'>Countries</option>
//every country option
</select>
<div id="card-element"></div>
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
JavaScript:
// JavaScript Document
// Create a Stripe client.
var stripe = Stripe('pk_test_PHnlKn4Jd72hlJjWPtQqDR1G00U2vyOtMP');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {
style: style,
hidePostalCode:true,
})
;
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card,tokenData).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
and php:
<?php
require_once('../vendor/autoload.php');
require_once('config.php');
\Stripe\Stripe::setApiKey('sk_test_key');
$POST = filter_var_array($_POST, FILTER_SANITIZE_STRING);
$token = $POST['stripeToken'];
$first = $POST['first'];
$last = $POST['last'];
$email = $POST['email'];
$phone = $POST['phone'];
$addy1 = $POST['addy1'];
$addy2 = $POST['addy2'];
$zip = $POST['zip'];
$city = $POST['city'];
$state = $POST['state'];
$country = $POST['country'];
$total = $POST['total'];
$customer = \Stripe\Customer::create(array(
"email" => $email,
"source" => $token,
"address" => array(
"line1" => "Test line 1",
"line2" => "Test Line 2",
"city" => "My City",
"postal_code" => "90210",
"state" => "CA",
)
));
$charge = \Stripe\Charge::create(array(
"billingAddress"=> true,
"shippingAddress"=>true,
"amount" => $total,
"currency" => "usd",
"description" => "BFM Purchase",
"customer" => $customer->id,
"shipping" => array(
"address" => array(
"name" => $first,
))
));
print_r($charge);
echo " break ";
print_r($customer);
?>
Okay, as far as things that I tried, I tried to add billing_details to the charge and customer objects, but I receive an error that billing_details in an unknown parameter. I think there is a spot where I can set that parameter to "true" but I don't know where and what to do from there. The next thing I see from the Stripe documentation is that I can pass the create token function in the js a second parameter which contains an object of the additional details I need, however, I don't know how to do this in the javascript.
Here: https://stripe.com/docs/stripe-js/reference
the docs refer to this as a dataToken, so then how can I create a custom Stripe token with shipping details and append that to the stripe token with the card info? Alternatively, I thought i could create a brand new token, pass it the important data from the stripe created token, then expand the shipping details in the new token once in the php file.
Any help is appreciated thank you.
I figured out the answer, all on my lonesome :(.
But basically it is much easier to add these details to a source and charging that source rather than a token. I followed the documentation from this link:
https://stripe.com/docs/sources/customers
Hope this can help a fellow struggler.
I am getting this error and I have no clue about this and trying to sort out the things and tried many things but nothing works. Kindly check the errors below:
Notice: Undefined index: stripeToken in
/opt/lampp/htdocs/fullbrick/thankYou.php on line 42 NULL Fatal error:
Uncaught Stripe\Error\InvalidRequest: Must provide source or customer.
in /opt/lampp/htdocs/fullbrick/stripe-php/lib/ApiRequestor.php:181
from API request 'req_cuGvSG7abb9bzS' Stack trace: #0
/opt/lampp/htdocs/fullbrick/stripe-php/lib/ApiRequestor.php(144):
Stripe\ApiRequestor::_specificAPIError('{\n "error": {\n...', 400,
Array, Array, Array) #1
/opt/lampp/htdocs/fullbrick/stripe-php/lib/ApiRequestor.php(430):
Stripe\ApiRequestor->handleErrorResponse('{\n "error": {\n...', 400,
Array, Array) #2
/opt/lampp/htdocs/fullbrick/stripe-php/lib/ApiRequestor.php(97):
Stripe\ApiRequestor->_interpretResponse('{\n "error": {\n...', 400 ,
Array) #3
/opt/lampp/htdocs/fullbrick/stripe-php/lib/ApiOperations/Request.php(56):
Stripe\ApiRequestor->request('post', '/v1/charges', Array, Array) #4
/opt/lampp/htdocs/halfdrink/stripe-php/lib/ApiOperations/Create.php(23):
Stripe\ApiResource::_staticRequest('post', '/v1/charges', Array, NULL)
5 /opt/lampp/htdocs/fullbrick/thankYou.php(53): Stripe\Charge::create(Array) #6
{main} in
/opt/lampp/htdocs/fullbrick/stripe-php/lib/ApiRequestor.php on line
181
The code is:
<script>
// Errors For Stripe Payment Card Check
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Create a token or display an error when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the customer that there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
// Custom styling can be passed to options when creating an Element.
var style = {
base: {
// Add your base input styles here. For example:
fontSize: '16px',
color: "#32325d",
}
};
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
</script>
<form action="thankYou.php" method="post" id="payment-form">
<span class="bg-danger" id="payment_errors"></span>
<span class="bg-danger" id="card-errors"></span>
<div class="form-group col-md-6">
<label for="full_name">Full Name:</label>
<input class="form-control" type="text" name="full_name" id="full_name">
</div>
//Same as Email div, phone,address,city,state,zipcode,country,cardname,cardnumber,exp month, exp year, cvc
<button type="submit" class="btn btn-primary" id="checkout_button" style="display:none;">Check Out >></button>
</form>
On thanYou.php
//Getting Variable details like
$full_name = $_POST['full_name']; // same as email,phone, address,city ...
$metadata = array(
"cart_id" => $cart_id,
"tax" => $tax,
"sub_total" => $sub_total,
);
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_hiQjZlN9oJ9GcLGAlPVwAvfq"); // secret Key
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
$token = $_POST['stripeToken']; // Here not getting token
var_dump($token);
try{ . // Here not getting inside the try because token is null
$charge = \Stripe\Charge::create([
'amount' => 999,
'currency' => 'usd',
'description' => 'Example charge',
'source' => $token,
'receipt_email' => $email,
'metadata' => $metadata,
]);
}catch(\Stripe\Error\card $e){
echo $e;
}
This ApiRequestor.php is the main problem I guess.
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');
});
})