0

I need to wait for a certain ajax request to complete before going on. Since this request is triggered from different anchors, I wrapped it in a function. What happens after the function with the first ajax has finished, is a second ajax request.

At first, I tried to wait for the first to finish using $.ajaxComplete() which ran into an endless loop because of the second ajax request performed thereafter.

I found some samples about using $.when but none of them showed whether it's possible to use a method instead deferreds.

Here's what I'd like to do:

$.when( functionFirstAjaxCall(data) ).then( function() {
    // after first ajax request has finished, do the following:
    $.ajax({
        //...
    });
});

Does functionFirstAjaxCall() need to have a certain return value or how can I get this one working? By the way, the solution doesn't need to use $.when.

Update: I got it working by creating a custom event as Vandesh has advised.

function first() {
    $.ajax({
        // ...
        success: function (d) {
            $.event.trigger({
                type: "finished",
                data: d
            });
         }
    });
}

$(document).on('finished', second());

Anyway, would there be a simple solution by using $.when?

Explicat
  • 1,075
  • 5
  • 16
  • 40
  • create a function with the second ajax and run it in `success:function(){...}` or `done:` from the first ajax? – Spokey Oct 07 '13 at 13:45
  • `success` is deprecated as of JQuery 1.8 - http://api.jquery.com/jQuery.ajax/ – Vandesh Oct 07 '13 at 13:49

2 Answers2

3

Yes we can! Dose something like this work for you?

function first() {
    var a = $.ajax({
        // ...
    });
    return a.promise();
}

first().done(function(){
    //Im done
});
reyaner
  • 2,799
  • 1
  • 12
  • 17
1

You can do something like -

$.ajax({// First AJAX call
    url: ""
}).done(function() {
    $.ajax({//Second AJAX call on completion of first
        url: ""
    }).done(function() {

    });
});

Find more on usage of $.ajax()

Vandesh
  • 6,368
  • 1
  • 26
  • 38
  • No, the first ajax is triggered on more occasions. The two don't go hand in hand. That's why I packed it into a function. I can't do `functionFirstAjaxCall().done(function(){ ... });` can I? – Explicat Oct 07 '13 at 13:54
  • 2
    You can try that using jQuery events - .bind() and .trigger() http://api.jquery.com/category/events/ Write your custom event which will trigger when your function is completed and bind the second AJAX call to that event – Vandesh Oct 07 '13 at 14:06