Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gatts's avatar
Level 1

display ajax errors with stripe

Hello guys!

Just over 2 months ago I started making a website in laravel in my spare time to help a family member, and so far with some difficulty I managed to do everything I wanted, but now I think I have reached the limit, and I am already very confused!

The real problem:

I have a checkout page that have 3 methods of payment and that shows validations in an ajax div when I fail, but when I choose the stripe, it goes to another page and shows the error.

I know that the code is incomplete, but i dont know how to do it.

My objective is to show the .print-error-msg errors on stripe too without going to other page.


    // 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('checkOrder');
        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();
    }

    $(document).ready(function () {

        // Create a Stripe client.
        var stripe = Stripe(
            'pk_test_...
        );

        // 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.on('change', function (event) {
            var displayError = document.getElementById('card-errors');

            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        $('#checkBtn').on('click', function (e) {
            e.preventDefault();

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            if ($('#pagamentoSelector').val() == 'pag3') {

                document.getElementById('checkBtn').disabled = true;

                var options = {
                    name: document.getElementById('name_on_card').value,
                    address_line1: document.getElementById('address').value,
                    address_city: document.getElementById('city').value,
                    address_state: document.getElementById('country').value,
                    address_zip: document.getElementById('zip').value
                }

                stripe.createToken(card, options).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;

                        // Enable the submit button
                        document.getElementById('checkBtn').disabled = false;
                    } else {
                        // Send the token to your server.
                        stripeTokenHandler(result.token);
                    }
                });
            } else {
                $.ajax({
                    method: 'POST',
                    url: '/checkout-order', // This is the url we gave in the route
                    data: $('#checkOrder').serialize(),
                    success: function (result) { // What to do if we succeed
                        if ($.isEmptyObject(result.error)) {

                            let timerInterval

                            Swal.fire({
                                position: 'center',
                                icon: 'success',
                                title: 'Obrigado!',
                                html: 'Encomenda realizada com sucesso',
                                footer: '(A voltar à página principal)<br><br><b>Foi-lhe enviado um e-mail com toda a informação da encomenda<b/>',
                                allowOutsideClick: false,
                                allowEscapeKey: false,
                                allowEnterKey: false,
                                timer: 5000,
                                timerProgressBar: true,
                                onBeforeOpen: () => {
                                    Swal.showLoading()
                                    timerInterval = setInterval(() => {
                                        const content = Swal
                                            .getContent()
                                        if (content) {
                                            const b = content
                                                .querySelector('b')
                                            if (b) {
                                                b.textContent = Math
                                                    .ceil(swal
                                                        .getTimerLeft() /
                                                        1000)
                                            }
                                        }
                                    }, 100)
                                },
                                onClose: () => {
                                    clearInterval(timerInterval)
                                }
                            }).then((result) => {
                                /* Read more about handling dismissals below */
                                if (result.dismiss === Swal.DismissReason.timer) {
                                    console.log('I was closed by the timer')
                                    window.location = '/';
                                }
                            })
                        } else {
                            printErrorMsg(result.error);
                            $('html, body').animate({
                                scrollTop: ($('.print-error-msg').offset().top -
                                    100)
                            }, 500, 'linear');
                        }
                    }
                });
            }

            function printErrorMsg(msg) {
                $(".print-error-msg").find("ul").html('');
                $(".print-error-msg").css('display', 'block');
                $.each(msg, function (key, value) {
                    $(".print-error-msg").find("ul").append('<li>' + value + '</li>');
                });
            }
        });
    });

The stripe is working when the validation is ok!

Sorry for my english and tks in advance!

0 likes
0 replies

Please or to participate in this conversation.