jQuery - Resume form submit after ajax call

前端 未结 3 1611
萌比男神i
萌比男神i 2020-12-05 22:02

Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?

At the moment it gets to the success bit b

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 22:30

    Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.

    Here is my working code:

    $(document).ready(function() {
        var testing = false;
        $('#btn-login').on('click', function() {
            $.ajax({
                url: $('form').attr('action'),
                type: 'post',
                data: $('form').serialize(),
                async: false,
                success: function(data) {
                    if (data == 'true')
                    {
                        testing = true;
                        $('form').attr('action', 'https://example.com');
                        $('form').submit();
                    }
                    else
                    {
                        alert('Your username/password are incorrect');
                    }
                },
                error: function() {
                    alert('There has been an error, please alert us immediately');
                }
            });
    
            return testing;
        });
    });
    

提交回复
热议问题