steveosoule
6/25/2013 - 5:22 PM

$.ajax() & setTimeout() Callbacks

$.ajax() & setTimeout() Callbacks

// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call

/* ---- AJAX CallBacks ---- */
function foo(callback) {
    $.ajax({
        // ...
        success: function(response) {
            // e.g. filter the response
            callback(filtered_response);
        }
    });
}

/* ---- AJAX Deferred objects / promises ---- */
function foo() {
    return $.ajax(...);
}

foo().done(function(result) {
    // code depending on result
}).fail(function() {
    // an error occurred
});

/* ---- Set Timeout Callback ---- */
function onComplete(a){
    alert(a);
}

function getFive(whenDone){ 
    var a;
    setTimeout(function(){
         a=5;
         whenDone(a);
    },10);
}

getFive(onComplete);