简体   繁体   中英

Registration form + Stripe JS - I have to click submit twice

I have a registration page that includes Stripe JS. Once the user has filled all fields, they click submit and nothing happens except an error Uncaught SyntaxError: Unexpected token < in JSON at position 0 in the console. If I then click submit again, it works as expected. I know what the problem is, I just don't know how to fix it. StripeToken is not being appended on the first "submit" but is on the second.

I've tried triggering the form submission twice with jQuery. I've tried putting everything in functions and running them in order. To my own (limited) knowledge, I've tried as much as I can.

    document.getElementById("submitbtn").style.display = "none";
    var tabTitles = ['Let\'s get to know eachother...', 'We have to make sure...', 'Where\'s Wally?', 'Something to remember...', 'It\'s just business...'];
    var currentTab = 0;
    showTab(currentTab);

    function showTab(n) {
        var x = document.getElementsByClassName("tab");
        x[n].style.display = "block";
        if (n == 0) {
            document.getElementById("prevBtn").style.display = "none";
        } else {
            document.getElementById("prevBtn").style.display = "inline";
        }
        if (n == (x.length - 1)) {
            document.getElementById('submitbtn').style.display = "inline";
            document.getElementById("nextBtn").style.display = "none";
            document.getElementById("nextBtn").classList.add("initpayment");
        } else {
            document.getElementById("nextBtn").innerHTML = "Next";
            document.getElementById('submitbtn').style.display = "none";
            document.getElementById("nextBtn").style.display = "inline";
        }
        document.getElementById("tabTitle").innerHTML = tabTitles[n];
        fixStepIndicator(n);
    }

    function nextPrev(n) {
        var x = document.getElementsByClassName("tab");
        if (n == 1 && !validateForm())
            return false;
        x[currentTab].style.display = "none";
        currentTab = currentTab + n;
        showTab(currentTab);
    }
// TODO: Sort this- invalid class added but overridden by parent backgorund-color:none
    function validateForm() {
        var x, y, i, valid = true;
        x = document.getElementsByClassName("tab");
        y = x[currentTab].getElementsByTagName("input");
        for (i = 0; i < y.length; i++) {
            if (y[i].value == "") {
                y[i].className += " invalid";
                valid = false;
            }
        }
        if (valid) {
            document.getElementsByClassName("step")[currentTab].className += " finish";
        }
        return valid;
    }

    function fixStepIndicator(n) {
        var i, x = document.getElementsByClassName("step");
        for (i = 0; i < x.length; i++) {
            x[i].className = x[i].className.replace(" active", "");
        }
        x[n].className += " active";
    }

    var stripe = Stripe('<?php echo $StripePublishKey; ?>');
    var elements = stripe.elements();
    var card = elements.create('card');
    card.mount('#card-element');

    $(document).ready(function () {
        $(document.body).on('change', "#PID_select", function () {
            var optPrice = $("#PID_select option:selected").data('price');
            $('#charge_amount').empty().html(optPrice);
        });

        var form = document.getElementById('regForm');
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            $('body').addClass('loading');

            stripe.createToken(card).then(function (result) {
                if (result.error) {
                    $('body').append('<div class="pgn-wrapper" data-position="bottom" style="left:0px;"><div class="pgn pgn-bar"><div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><span>' + result.error.message + '</span></div></div></div>');
                } else {
                    $('[name="stripeToken"]').empty().val(result.token.id)
                }
            });

            var FData = $('#regForm').serializeArray();

            $.post('register', FData, function (registerReturn) {
                var $Return = JSON.parse(registerReturn);

                if ($Return.status === 'complete') {
                    window.location.replace('login?RD=3');
                } else if ($Return.status === '3d_required') {
                    var paymentIntentSecret = $Return.PIK;

                    stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
                        if (result.error) {
                            $.post('register', {errorReg: true, token: $Return.token});
                            $('body').append('<div class="pgn-wrapper" data-position="bottom" style="left:0px;"><div class="pgn pgn-bar"><div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><span>' + result.error.message + '</span></div></div></div>');
                            $('body').removeClass('loading');
                        } else {
                            $.post('register', {finishReg: true, token: $Return.token});
                            window.location.replace('login?RD=3');
                        }
                    });
                } else if ($Return.status === 'error') {
                    $('body').append($Return.response);
                    $('body').removeClass('loading');
                }
            });
            $('body').removeClass('loading');
        });
    });

Error message on the first submission attempt: Uncaught SyntaxError: Unexpected token < in JSON at position 0.

Results on first attempt: none. Results on second attempt: as expected

Expected result: on first submission attempt, stripe generates the token, appends it to the form and the submission continues as normal.

I didn't ur code tbh but according to ur title here's how to do it:

set a var with a default value:

var numofclicks = 0;

now just below that u just add the function onclick that u should create on the button ur trying to kinda toggle with, for ex lets set the name of the funtion clicked() so:

function clicked(){
 numofclick++;
 if(numofclicks = 1){
 //do stuff here
 }

 }

Resolved.

document.getElementById("submitbtn").style.display = "none";
    var tabTitles = ['Let\'s get to know eachother...', 'We have to make sure...', 'Where\'s Wally?', 'Something to remember...', 'It\'s just business...'];
    var currentTab = 0;
    showTab(currentTab);

    function showTab(n) {
        var x = document.getElementsByClassName("tab");
        x[n].style.display = "block";
        if (n == 0) {
            document.getElementById("prevBtn").style.display = "none";
        } else {
            document.getElementById("prevBtn").style.display = "inline";
        }
        if (n == (x.length - 1)) {
            document.getElementById('submitbtn').style.display = "inline";
            document.getElementById("nextBtn").style.display = "none";
            document.getElementById("nextBtn").classList.add("initpayment");
        } else {
            document.getElementById("nextBtn").innerHTML = "Next";
            document.getElementById('submitbtn').style.display = "none";
            document.getElementById("nextBtn").style.display = "inline";
        }
        document.getElementById("tabTitle").innerHTML = tabTitles[n];
        fixStepIndicator(n);
    }

    function nextPrev(n) {
        var x = document.getElementsByClassName("tab");
        if (n == 1 && !validateForm())
            return false;
        x[currentTab].style.display = "none";
        currentTab = currentTab + n;
        showTab(currentTab);
    }

    function validateForm() {
        var x, y, i, valid = true;
        x = document.getElementsByClassName("tab");
        y = x[currentTab].getElementsByTagName("input");
        for (i = 0; i < y.length; i++) {
            if (y[i].value == "") {
                y[i].className += " invalid";
                valid = false;
            }
        }
        if (valid) {
            document.getElementsByClassName("step")[currentTab].className += " finish";
        }
        return valid;
    }

    function fixStepIndicator(n) {
        var i, x = document.getElementsByClassName("step");
        for (i = 0; i < x.length; i++) {
            x[i].className = x[i].className.replace(" active", "");
        }
        x[n].className += " active";
    }

    var stripe = Stripe('<?php echo $StripePublishKey; ?>');
    var elements = stripe.elements();
    var card = elements.create('card');
    card.mount('#card-element');

    $(document).ready(function () {
        $(document.body).on('change', "#PID_select", function () {
            var optPrice = $("#PID_select option:selected").data('price');
            $('#charge_amount').empty().html(optPrice);
        });

        var form = document.getElementById('regForm');
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            $('body').addClass('loading');
            stripeToken();
        });

        function stripeToken() {
            stripe.createToken(card).then(function (result) {
                if (result.error) {
                    $('body').append('<div class="pgn-wrapper" data-position="bottom" style="left:0px;"><div class="pgn pgn-bar"><div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><span>' + result.error.message + '</span></div></div></div>');
                } else {
                    handleForm(result.token.id.toString());
                }
            });
        }

        function handleForm(token) {
            var FData = $('#regForm').serializeArray();
            FData.push({name: 'stripeToken', value: token});

            $.post('register', FData, function (registerReturn) {
                var $Return = JSON.parse(registerReturn);

                if ($Return.status === 'complete') {
                    window.location.replace('login?RD=3');
                } else if ($Return.status === '3d_required') {
                    var paymentIntentSecret = $Return.PIK;

                    stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
                        if (result.error) {
                            $.post('register', {errorReg: true, token: $Return.token});
                            $('body').append('<div class="pgn-wrapper" data-position="bottom" style="left:0px;"><div class="pgn pgn-bar"><div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><span>' + result.error.message + '</span></div></div></div>');
                            $('body').removeClass('loading');
                        } else {
                            $.post('register', {finishReg: true, token: $Return.token});
                            window.location.replace('login?RD=3');
                        }
                    });
                } else if ($Return.status === 'error') {
                    $('body').append($Return.response);
                }
            });
            $('body').removeClass('loading');
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM