Intercept form, add data, ajax, then submit.

2019-09-06 13:51发布

I'd like to intercept a form submission, ajax it to one location and then post the form. Below is my attempt with my failures commented out. Any insight into where I'm going wrong would be appreciated, as always.

A note into why I'm doing what I'm doing: I would like to store a complete copy of the form, HTML and all, but still process selected fields as a typical form submit. My ajax saves the HTML as intended, but stops the form submission. Removing the preventDefault() causes the form to submit before the ajax is successful.

$('#myForm').submit(function(event) {
    event.preventDefault();
    $.ajax({
        type: 'POST',
        url: '../../lib/processCompleted.php',
        cache: false,
        dataType: 'text',
        data: { PracticeID: PracticeID },

        success: function (data) {
            alert('success');
            // I would then like to submit the form as usual.
            //return true; 
            //$('#myForm').submit();
        },
        error: function () {
            alert('boo');
        }
    });
});

Cheers

1条回答
仙女界的扛把子
2楼-- · 2019-09-06 14:29

when you call $('#myForm').submit(); again the submit handler will get called which will prevent the form submission. In this case creating a infinite loop of the ajax requests.

Try

$('#myForm')[0].submit();

Demo: Fiddle

查看更多
登录 后发表回答