Form Submission and redirection

Viewed 177

I'm trying to implement stripe payment on my website but before the customer goes to stripe checkout I need to collect the data from the form.

I have the code below but the form is not being submitted. When I click the button it goes directly to Stripe. If you guys have any idea how to make this form works it would be wonderful! Thank you in advance.


<form id="booking-form" action="<?php echo esc_url( ct_get_thankyou_page() ); ?>">  

<input type="text" class="form-control" name="first_name" value="">

<input type="text" class="form-control" name="last_name" value="">

<input type="text" class="form-control" name="email" value="">

<button type="submit" class="book-now-btn" id="book-now-btn" <?php echo esc_html__( 'Pay Now', 'bookings' ) ?></button>


</form>



<script>
const url = '/stripe_checkout_integration_php/stripe_charge.php'; // 


var buyBtn = document.getElementById('book-now-btn');
var responseContainer = document.getElementById('paymentResponse');

    
// Create a Checkout Session with the selected product
var createCheckoutSession = function (stripe) {
  
    return fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            checkoutSession: 1,
        }),
    }).then(function (result) {

        return result.json();

       


    });
};

// Handle any errors returned from Checkout
var handleResult = function (result) {
    if (result.error) {
        responseContainer.innerHTML = '<p>'+result.error.message+'</p>';
    }
    buyBtn.disabled = false;
    buyBtn.textContent = 'Buy Now';
};

// Specify Stripe publishable key to initialize Stripe.js
var stripe = Stripe('<?php echo STRIPE_PUBLISHABLE_KEY; ?>');

buyBtn.addEventListener("click", function (evt) {
    buyBtn.disabled = true;
    buyBtn.textContent = 'Please wait...';



    createCheckoutSession().then(function (data) {
        if(data.sessionId){
            stripe.redirectToCheckout({
            }).then(handleResult);
        }else{
            handleResult(data);
        }
    });
});
</script>
1 Answers

You've created a race condition and this is more or less expected. You're redirecting to Stripe Checkout and also expecting to POST form data with a single click without any explicit management of this entwined behaviour.

Instead of relying on form post, you'll want to either make an explicit server call with the data you need, or pass the data in your createCheckoutSession fetch call and process it there.

Related