Page not redirecting to stripe checkout after it passed form validation
You want to prevent the default behaviour of submiting the form. So do:
checkoutButton.addEventListener('click', function(event) {
...
if(isFormValid==true) {
event.preventDefault();
References
- Prevent Default on Form Submit
- Event.preventDefault()
Right now your code is only attaching the click
listener if the form is valid at page load. In the absence of other form behavior, clicking a button in a form submits it back to the page it came from, which is why it looks like a page refresh.
You need to move the form check inside the button click event handler like so:
<script>
(function() {
var stripe = Stripe('pk_test_xxx');
var checkoutButton = document.getElementById('checkout-button-sku_xxx');
checkoutButton.addEventListener('click', function() {
if($('#tcform')[0].checkValidity()){
// When the customer clicks on the button, redirect
// them to Checkout.
stripe.redirectToCheckout({
items: [{
sku: 'sku_xxx',
quantity: 1
}],
// Do not rely on the redirect to the successUrl for fulfilling
// purchases, customers may not always reach the success_url after
// a successful payment.
// Instead use one of the strategies described in
// https://stripe.com/docs/payments/checkout/fulfillment
successUrl: window.location.protocol + '//www.xxx.com',
cancelUrl: window.location.protocol + '//www.xxx.com',
})
.then(function(result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
}
});
})();
But it might be even better to listen to the form's submit
event (https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event):
$('#tcform').on('submit', function() {
stripe.redirectToCheckout({
...
});
});
The submit
event is only emitted after the form is validated.