AlexF
AlexF

Reputation: 33

ASP.NET MVC Action on Synchronous AJAX Requests

I am looking for an MVC implementation equivalent in functionality to the WebForms ajax request handlers below:

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function());
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function());

A very similar question (link below) was answered with a reference to the global .ajax event handlers, but as all of my calls are synchronous I am having the issue that it is firing the ajax finished event at the end of each individual ajax request, and I want it to start with the first and end when the final one finishes. I tried using ajaxStart and ajaxStop which the documentation suggests should be exactly what I am looking for, but I belive that these would only work as intended with async ajax requests.

(ASP.NET MVC 4 Action on AJAX Request)

Is there any way to do this using the jQuery built in ajax event handlers, or any alternative method for synchronous requests?

Upvotes: 1

Views: 1032

Answers (3)

Ravi
Ravi

Reputation: 475

jquery don't have anything inbuilt like that but you can do one thing, take one counter and initialize with 0 and in each ajaxstart you can increment by 1 and in success/error of ajax decrement counter by 1 and as soon as you get value of counter as 0 means all request is over.

Upvotes: 0

p e p
p e p

Reputation: 6674

You can use jQuery's .when (in combination with .apply) which allows you to execute a callback function based on any number of Deferred objects (which are returned by jQuery .ajax calls). Check out the fiddle and open up dev tools, if you watch the log you will see the correct order of events. First 'started' is logged, then a number of 'ajax response' messages are logged, and finally the 'complete' message is logged at the end of all requests.

Fiddle: http://jsfiddle.net/efjmcm49/

var ajaxCalls = [];
console.log('started');
for(var i = 1; i <= 5; i++){
    var currentCall = $.ajax({
        url: '/echo/json',
        type: 'GET',
        success:function(data){
            console.log('ajax response');
        }
    });

    ajaxCalls.push(currentCall);
}

$.when.apply($, ajaxCalls).done(function () {
    console.log('complete');
});

Upvotes: 1

ChrisV
ChrisV

Reputation: 1309

In a series of synchronous requests, jQuery cannot know when you are done making all of them. How would it know that you aren't just about to start another one?

If the requests are synchronous can't you just use normal program flow? Like:

ajaxStart(); //execute arbitrary code

while(condition) {
    //ajax requests here
}

ajaxStop(); //execute arbitrary code

Upvotes: 1

Related Questions