Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple AJAX requests in jQuery

I have a function that pulls data from two locations and places the returned content on a modal dialog that is displayed to the user.

Both requests are asynchronous because they're cross-domain. The problem lies in that I don't want to display the modal until both requests have finished loading. How can I check to make sure both requests have finished before loading the modal?

I have tried placing the openModal functions in the success handler of the second request and that works when the first requests finishes loading before the second request, but sometimes this isn't the case.

Here's a copy of my code:

function loadData(id) {
$.ajax({
    type: 'GET',
    url: 'https://someurl.com/v1.0/controller1/' + id,
    dataType: 'jsonp',
    success: function(data) {
        // Do some stuff to the data
    }
});

$.ajax({
    type: 'GET',
    url: 'https://someurl.com/v1.0/controller2/' + id,
    dataType: 'jsonp',
    success: function(data) {
        // Do some stuff to the data

        openModal();
    }
});
}

function openModal() {
// Open the modal
}
like image 610
Austin Avatar asked Feb 10 '11 16:02

Austin


1 Answers

Check out the new version of jQuery -- 1.5. It has support for exactly your problem, you can check out this blog post for the solution of your problem: http://www.erichynds.com/jquery/using-deferreds-in-jquery/

like image 123
Tim Avatar answered Sep 22 '22 05:09

Tim