views:

65

answers:

1

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.

+2  A: 

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

            }
        });
});
redsquare
+1 this is what one usually does. No, you can't run an asynchronous function synchronously, or vice-versa. That would require language features like threads or coroutines, which JavaScript doesn't have.
bobince
You could do a synch ajax call, could....but I never would!
redsquare
Thanks, it (mostly) worked. Nothing wrong with your code, just had to add a hidden field to check on the php side on submit since there are multiple submit buttons on the form that do different things.
Peter