Question

I have the following javascript:

function someFunction(string) {
    $.ajax({
        type: "GET",
        url: "some_endpoint_returning_json",
        async: false,
        data: "param=" + string,
        beforeSend: function() {
            $.blockUI({ message: '<h1><img src="static/busy.gif" /> Just a moment...</h1>' });
        },
        complete: function () {
            $.unblockUI();
         },
        dataType: "json",
        success: function(data) {
            window.alert(data.status);
        }
    });
}

I want the UI to block with the included message before sending the ajax request, then remove the message, unblock the ui and then perform the success function.

Currently here is what is happening:

  1. the UI blocks, but doesn't display the message
  2. The success window alert pops up
  3. Upon confirming the alert window, the BlockUI message pops up for a split second, then the UI unblocks and the page returns to its initial state
Was it helpful?

Solution

If you set async to false, the browser will halt the execution of everything while the ajax request is served. Although beforeSend does execute before the ajax request is sent, the synchronous request may occur so quickly that the browser doesn't actually refresh the screen and show your $.blockUI changes. You do get to see them for a very short time after the ajax completes (when they are removed immediately).

If you must use async, you may be able to get around this by calling $.blockUI separately and setting a short timeout (100 MS perhaps) before starting the ajax request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top