oompahloompah
oompahloompah

Reputation: 9343

jQuery blockUI and AJAX POST

I am using jQuery BlockUI in a project. For a particular user action, I want to block the UI, and then POST data to the server. When the timeout event occurs OR the server returns, I want to unblock the page.

I can't seem to implement this behaviour. This is what I have so far (not working)

$(document).ready(function(){
    $('#test').click(function(event){
        $.blockUI({ message: $('#mydiv') });

        $.ajax({
              type: 'POST',
              url: 'www.example.com',
              data: somedata,
              dataType: "json"
        });

        setTimeout(function() {
                $.unblockUI({
                    onUnblock: function(){ 
                        alert('onUnblock');
                    }
                });
            }, 2000);
});

can anyone spot what I may be doing wrong?

Upvotes: 0

Views: 7218

Answers (2)

dmgig
dmgig

Reputation: 4568

I think you need to set ajax's own success, error, and timeout properties for this. Forget using the other setTimeout.

here are the docs.

http://api.jquery.com/jQuery.ajax/

more like:

 $.ajax({
              type: 'POST',
              url: 'www.example.com',
              data: somedata,
              dataType: "json",
              timeout: /*your time*/,
              success: function(result){ /*unblock*/ },
              error: function (xhr, ajaxOptions, thrownError){ /*unblock*/ }
        });

Upvotes: 4

aiham
aiham

Reputation: 3614

Use the complete callback

    $.ajax({
          type: 'POST',
          url: 'www.example.com',
          data: somedata,
          dataType: "json",
          complete: function(){
            // unblock stuff here
          }
    });

The difference between success and complete is that complete is called whether or not the ajax call succeeded. If you only use success, then the UI will stay blocked if the AJAX call fails.

Upvotes: 0

Related Questions