Search code examples
jqueryformssubmitblocking

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


Is there a way, using jQuery, to 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.


Solution

  • 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();
                    } 
    
                }
            });
    });