Sudeep's Blog

Disorganized Thoughts in Organized Manner

jQuery, json and synchronous callbacks
jQuery's getJSON is an asynchronous callback, meaning the function returns at an unknown point in future, when the remote request completes. What if we want it to return some value to the calling function? What if we want it to update a global variable that is later going to be read by some other method? The answer is quite simple, and I found it by some googling and stack-overflowing ( stoverflowing ; wow, Oxford should totally add that word now). The trick is to call a detailed $.ajax method which accepts a Boolean async argument. Simply setting async: false does the trick. So, here is a sample call to getJSON $.getJSON(url, function(data) { doSomething }); This call, as we noted, is asynchronous. It can be converted into a synchronous callback as: $.ajax({ type: 'GET', url: 'whatever', dataType: 'json', success: function() { doSomething }, data: {}, async: false }); Notice the last async: false argument. Easy peasy!
Tweet
Back to Home