如何在提交函数内的ajax回调中提交表单

时间:2016-12-13 15:26:22

标签: javascript jquery

我在提交功能中正在做一个AJAX表单帖子。如果成功回调触发,我想提交表单。我现在的方式,表单提交,但是,当然,它陷入了无限循环。如何正确退出提交功能,以便表单只提交一次?

$(function() {
    var ccform = $('#ccForm'),
        ccnumber = $('#number'),
        ccexpiry = $('#expiry'),
        cartForm = $("#ShoppingCart");

    // If Qty Avail Exceeded is True Hide CC Payment Option and Form
    if ($('#qtyAvailExceeded').val() === "True") {
        //$('#ccOpt, #ccForm').hide();
    }

    // If Credit Card Payment Method Selected Show CC Form
    $('#paymethod').on('change', function() {
        if ($(this).val() == 'CCOpt') {
            setTimeout(function() {
                ccnumber.focus();
            }, 0);

            // Show CC Fields if CC option selected as payment method
            ccform.removeClass('hide');

            // Post CC to Paymentvalidate
            cartForm.submit(function(e) {

                var form = $(this),
                    action = $('#Action');

                action.val('PAYMENTVALIDATE');

                // Post Form if it validates
                if (form.parsley().isValid()) {
                    var pay = $.ajax({
                        url: "webcatpageserver.exe",
                        method: "POST",
                        dataType: "json",
                        data: {
                            Action: $('#Action').val(),
                            Ship_Via: $('#shipVia').val(),
                            OrderMode: $('#orderMode').val(),
                            Order_Notes: $('#orderNotes').val(),
                            amountpaid: $('#amtPaid').val(),
                            cardnum: $('#cardNum').val(),
                            expiry: $('#expiry').val(),
                            cvc: $('#cvv').val(),
                            cardholder: $('#name').val()
                        },
                        cache: false
                    });
                    pay.done(function(data) {
                        if (data.DidValidate === false) {
                            ccAlert.html(data.ErrorMessage);
                            ccAlert.removeClass('hide');
                        } else if (data.DidValidate === true) {
                            ccAlert.html(data.ErrorMessage).addClass('hide');
                            action.val('SendOrderVerify');
                            form.submit();
                        }
                    });
                    pay.fail(function(xhr, status, error) {
                        console.log(xhr.responseText);
                    });
                }
            });
        } else {
            ccform.addClass('hide');
        }

        e.preventDefault();

    });

    // If CC Option Unavailable, Default to the Account Payment Option
    if ($('#ccOpt').length === 0) {
        $('#paymethod').val("AcctOpt");
    }

    // Initialize CC Form
    $('#ccForm').card({
        container: '.card-wrapper',
        width: 360,
        formSelectors: {
            numberInput: 'input#number',
            expiryInput: 'input#expiry',
            cvcInput: 'input#cvv',
            nameInput: 'input#name'
        }
    });

    // Check CC Card Type
    ccnumber.keyup(function() {
        var cvv = $('#cvv');
        if ($('.jp-card').hasClass('jp-card-amex')) {
            cvv.attr({
                'data-parsley-minlength': 4,
                'data-parsley-maxlength': 4
            });
        } else {
            cvv.attr({
                'data-parsley-minlength': 3,
                'data-parsley-maxlength': 3
            });
        }
    });

    // Remove Spaces from Card Number Before Submit to Paymentvalidate
    ccnumber.on('change', function() {
        var ccnumberNoSpaces = $('#number').val().replace(/\s+/g, '');
        $('#cardNum').val(ccnumberNoSpaces);
    });
});

合并更新 - 不工作

$(function() {
    var ccform = $('#ccForm'),
        ccnumber = $('#number'),
        ccexpiry = $('#expiry'),
        cartForm = $("#ShoppingCart");

    cartForm.submit(function(e) {

        var form = $(this),
            action = $('#Action'),
            ccAlert = $('#ccAlert');

        if (action.val() != 'SendOrderVerify') {

            e.preventDefault();

            // Post Form if it validates
            if (form.parsley().isValid()) {
                action.val('PAYMENTVALIDATE');
                var pay = $.ajax({
                    url: "webcatpageserver.exe",
                    method: "POST",
                    dataType: "json",
                    data: {
                        Action: $('#Action').val(),
                        Ship_Via: $('#shipVia').val(),
                        OrderMode: $('#orderMode').val(),
                        Order_Notes: $('#orderNotes').val(),
                        amountpaid: $('#amtPaid').val(),
                        cardnum: $('#cardNum').val(),
                        expiry: $('#expiry').val(),
                        cvc: $('#cvv').val(),
                        cardholder: $('#name').val()
                    },
                    cache: false
                });
                pay.done(function(data) {
                    if (data.DidValidate === false) {
                        ccAlert.html(data.ErrorMessage);
                        ccAlert.removeClass('hide');
                    } else if (data.DidValidate === true) {
                        console.log('didvalidate');
                        ccAlert.addClass('hide');
                        action.val('SendOrderVerify');
                        form.submit();
                    }
                });
                pay.fail(function(xhr, status, error) {
                    console.log(xhr.responseText);
                });
            } else {
                ccform.addClass('hide');
            }
        }
    });
});

1 个答案:

答案 0 :(得分:0)

您希望以编程方式提交表单后跳过整个表单验证并重新提交。您已经在使用我们可以用来控制流量的action变量。 我将尝试在此示例中略微缩写您的代码:

 // Post CC to Paymentvalidate
 cartForm.submit(function(e) {
 var form = $(this),
    action = $('#Action');

    if( action.val() != 'SendOrderVerify' ){//avoids the resubmit
        action.val('PAYMENTVALIDATE');            
        // Post Form if it validates
        if (form.parsley().isValid()) {
            var pay = //ajax call

            pay.done(function(data) {
              if (data.DidValidate === false) {
                ccAlert.html(data.ErrorMessage);
                ccAlert.removeClass('hide');
              } else if (data.DidValidate === true) {
                ccAlert.html(data.ErrorMessage).addClass('hide');
                action.val('SendOrderVerify');
                form.submit();
              }
            });

            pay.fail(function(xhr, status, error) {
                console.log(xhr.responseText);
            });
        }
      e.preventDefault();
    }
});

由于您更改了action.val()值以指示您正在执行的操作,因此我们只在您的提交逻辑中使用它。现在如果action.val()=='SendOrderVeify'它将跳过额外的验证步骤(因为它们已经运行),反过来form.submit()将不会再次运行。因此没有提交循环。