Question

I have a couple of ajax requests that grab some data:

$.ajax({
    url: '/bin/MVC/Reporting/GetReportTemplates',
    type: "GET",
    success: function (data) {
        reportingMetaData.ReportTemplates = data.Data;
    }
});

$.ajax({
    url: '/bin/MVC/Reporting/GetReportTopTypes',
    type: "GET",
    success: function (data) {
        reportingMetaData.ReportTopTypes = data.Data;
    }
}

AFTER BOTH of these have returned, I want to run another function.

I'm aware of jquery deferred, but I have never used it, and am unsure how to apply it in this instance.

Could anyone assist?

Was it helpful?

Solution

var a1 = $.ajax({
    url: '/bin/MVC/Reporting/GetReportTemplates',
    type: "GET"
});
var a2 = $.ajax({
    url: '/bin/MVC/Reporting/GetReportTopTypes',
    type: "GET"
});
$.when(a1, a2).then(function() {
    //Both ajax requests have completed successfully
});

OTHER TIPS

You need $.when().

var req_1 = $.ajax({...});
var req_2 = $.ajax({...});
$.when(req_1, req_2).done(function(response_1, response_2) {
    //do something here when both requests done
});

It's also worth pointing out that $.when() can take deferred OR NON-deferred objects as arguments. This means it can act in cases where the request may be synchronous OR asynchronous. If you happen to be in the UK, an upcoming article in .NET magazine by me looks at this in more detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top