Jquery plugin blockUI not working with ajax

Mithril picture Mithril · Sep 26, 2012 · Viewed 19.6k times · Source

I want to block the current page when a specific ajax call is made and use a blockUI as a message box. I can't just use $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);

My code is the following..

bc.find('.submit').click(function (e) {
    e.preventDefault();
    if ($(this).hasClass('lock'))
        return;
    $.blockUI();
    $(this).addClass('lock');
    bc.submit();
});

var validator;
validator = bc.validate({
    ignore: '',
    rules: {
        UserName: {
            required: true
        }
    },
    messages: {
        UserName: 'must have',
    },
    submitHandler: function (form) {
        $.ajax({
            url: '/yyyy/xxxx',
            type: 'POST',
            data: postdata,
            complete: function () {
                bc.find('.submit').removeClass('lock');
            },
            success: function (data) {
                if (data.status == 'OK') {
                    $.blockUI({ message: 'OK' });
                    ......
                }
                else {
                    switch (data.status) {
                        case 'xxx':
                        ......
                    }
                    $.unblockUI();
                }
            },
            error: function () {
                $.unblockUI();
                alert('xxx');
            }
        });
    }
});

The scenario is that when I click the .submit button, the page is blocked and a ajax call is made to the server to get a data response. When the ajax call is successful, I unblock the current page and if data.status is 'OK', I show a message box (also based on blockUI plugin). Else I show an error on the current page, and then unblock it.

Edit at 2016, there is a edit which change the question meaning(maybe due to my very poor English at that moment), I have rolled change back here, and make it more clear, please do not change below again.

But in fact, only after ajax call is completed (debug step over the code in ajax complete handler), then see:

  1. first $.blockUI(); excuted
  2. execute $.blockUI({ message: 'OK' }) or not
  3. then $.unblockUI() be called

(Above is what I mean abnormal execution sequence of chrome or firefox debug tool in the answer.because blockui code should not be executed after ajax complete)

It's not what I want, and I can't figure this out.

Answer

Paresh Radadiya picture Paresh Radadiya · Mar 30, 2014

I had the same issue because i used sync ajax call that is aync is false

I solved it by making an ajax call async to true

$.ajaxSetup({ async :true});