开发者

Using jQuery to block form redirections on submit until the function finishes

Is there a way, using jQuery, t开发者_StackOverflow中文版o force a form to wait until a function is done executing before submitting?

I have a submit button on a multi-field form. I would like the submit button to hit a server to determine whether the current user has any items in the database, and if they have none, I would like it to pop up a confirmation window to ensure that the user is aware. If they have some items already, I would like it to skip the popup window and submit as normal.

I'm using something like this:

$('#done').click(function(event)
{
    $.post(asyncController + "/checkItems", function(response)
            {
                if(response != "true")
                {
                    var test = confirm('Are you sure?');
                    if(test)
                    {
                        //submit
                    } else
                    {
                        event.preventDefaultAction();
                    }
                }
            }
        );
});

Unfortunately, form doesn't wait for the javascript to finish executing and I get the pop up mid way through loading the next page.


Try the following. In summary it prevents the default submit action of the click event of the submit button, we then grab a reference to the form element and we submit this form if the result of the ajax call and confirm is true.

    $('#done').click(function(event) {

        //prevent submit
        event.preventDefault();

        //get form reference
        var frm = this.form;

        $.post(asyncController + "/checkItems", function(response) {

            if (response != "true") {

                var test = confirm('Are you sure?');

                if (test) {
                    //submit the form
                    frm.submit();
                } 

            }
        });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜