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?

2
  • create a function with the second ajax and run it in success:function(){...} or done: from the first ajax? Commented Oct 7, 2013 at 13:45
  • success is deprecated as of JQuery 1.8 - api.jquery.com/jQuery.ajax Commented Oct 7, 2013 at 13:49

2 Answers 2

3

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

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

first().done(function(){
    //Im done
});
Sign up to request clarification or add additional context in comments.

Comments

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()

2 Comments

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?
You can try that using jQuery events - .bind() and .trigger() 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.