Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event after all ajax calls are complete

I have a click event that fires off 3 ajax calls:

$("#button").click(function(e) {
    e.preventDefault();

    $.ajax(call1);
    $.ajax(call2);
    $.ajax(call3);

    some_function() //should fire off AFTER all ajax calls are complete
});

Is there a way for me to confirm all ajax calls have been fired BEFORE firing off my some_function() function?

Thanks in advance!

like image 563
Trung Tran Avatar asked Mar 10 '16 01:03

Trung Tran


People also ask

How do you check if all AJAX calls are completed?

jQuery ajaxStop() Method The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

How do I return data after AJAX call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

How do you trigger a change event after AJAX call?

ajax({ url, data: data, type: "POST", dataType: "json", success: function(cbdata) { update_table(cbdata); } }); } $('#selector'). on('click', changeDate); So you can call changeData() when you need it.

Which global event is triggered if an AJAX request?

The ajaxStart and ajaxStop events are events that relate to all Ajax requests together. This event is triggered if an Ajax request is started and no other Ajax requests are currently running.


2 Answers

You can use $.when

Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

$.when($.ajax(call1), $.ajax(call2), $.ajax(call3))
.done(function () {
     some_function();
});

If (for some reason) you have an array of promises, then you may call this method using Function.prototype.apply():

$.when.apply($, ajaxArray)
.done(function () {
   some_function();
});
like image 96
Matias Cicero Avatar answered Oct 17 '22 20:10

Matias Cicero


I suggest you to use async: false and put the $.ajax inside another ajax, somelike this...

$.ajax({
    async: false,
    // ...
    complete: function() {
        $.ajax({ // second ajax
            async: false,
            // ...
            complete: function() {
                $.ajax({ // second ajax
                    async: false,
                    // ...
                    complete: function() {
                         some_function();
                    }
                });
            }
        });
    }
});
like image 27
BrTkCa Avatar answered Oct 17 '22 21:10

BrTkCa