Search code examples
javascriptjqueryjsonsynchronize

jQuery - Block input until after $.getJson is done


I need to make sure that all user-input is blocked until the json data are recieved and processed. I read somewhere that I can do this with Deffered objects, but it doesn't seem to work. My code:

function checkDTCCardAvailability() {
    var defer = $.Deferred(),
    isAvailable = defer.then(function() {
        $('#pass-search-form').block({
            message: '<h4>Please Wait</h4>',
            css: {
                backgroundColor: '#0192af',
                color: '#f6d200'
            }
        });

        $.getJSON("site_url",{
            city: 'Athens',
            age: 25
        }, function(j) {
            //process data	        
            alert(j);
        }); //JSON call
    });

    defer.resolve();
    isAvailable.done(function() {
        // Enable form		
        $('#pass-search-form').unblock();
    });
}

Sometimes the screen will unblock before the alert shows up. Any ideas?


Solution

  • If you put the unblock() in your getJSON callback it will wait until the response:

    $.getJSON("site_url", {
        city: 'Athens',
        age: 25
    }, function (j) {
        //process data          
        alert(j);
    
        // Enable form      
        $('#pass-search-form').unblock();
    }); //JSON call