javascriptjqueryjquery-blockui

jQuery ajax beforeSend


I have a simple AJAX call that is executing a function on the beforeSend and on complete. They execute fine but the beforeSend is "seemingly" not executed until after the success.

On the beforeSend there is a "Please wait" notification. If I put a break after the function in the beforeSend then it will show that notification and then hit the success. Without the break point then it will sit there and think while waiting for the response and then my please wait notification will appear for a fraction of a second after the success is hit.

The desired functionality is to have the notification appear as soon as the request is sent so it displays while it is waiting for the response.

        $.ajax({
            type : 'POST',
            url : url,
            async : false,
            data : postData,
            beforeSend : function (){
                $.blockUI({
                    fadeIn : 0,
                    fadeOut : 0,
                    showOverlay : false
                });
            },
            success : function (returnData) {
                //stuff
            },
            error : function (xhr, textStatus, errorThrown) {
                //other stuff
            },
            complete : function (){
                $.unblockUI();
            }
        });

Solution

  • Your problem is the async:false flag. Besides the fact that it is bad practice (and really only makes sense in a very limited number of cases), it actually messes with the order of execution of the rest of the code. Here is why:

    It seems that somewhere in the blockUI code they are setting a setTimeout. As a result, the blockUI code waits a very short amount of time. Since the next instruction in the queue is the ajax() call, the blockUI execution gets placed right behind that. And since you are using async:false, it has to wait until the complete ajax call is completed before it can be run.

    In detail, here is what happens:

    If you would NOT use async:false, the execution would go as followed:

    Here are some jsFiddle examples to demonstrate the problem:

    Example 1: This is the situation you are experiencing. The blockUI text doesn't show until after the ajax call executes.

    Example 2: This is the exact same situation as yours, but with an alert before the ajax call. Because there is an alert, the timeout inside blockUI places the appearance of the blockUI text after the alert instead of after the ajax.

    Example 3: This is how it is supposed to work without async:false