2

I am executing simultaneous ajax request on a button click.

I have a table with a list of alarms and each row has it's own button that once clicked tries to clear the alarm in the db and then I remove it from the table.

I can click on these buttons one after another and trigger an ajax request.

Problem:

lets say I click on a button and for some reason this is taking time and the user manages to click on yet another button to start a new ajax.

I want to execute a script block in my ajax succes method ONLY if all the ajax requests in the current scope are finished.

code:

$(".signAlarm")
    .on("click",
        function () {
            var _this = $(this).parents(".alarmRow");
            var alarm = {
                Id: $(_this).data("id")
            }
            $.automation.worker.postJson("/Alarm/SigAlarm",
            JSON.stringify({ alarm }),
            function (data) {
                if (!$.automation.worker.ajaxActive()) {
                    // execute this if all the sign alarm attempts are finished                               
                }
                $(_this).remove();
            });
        });

ajaxActive function:

ajaxActive: function() {
    if ($.active) return true;

    return false;
}

when searching for an answer I found jquery.active which I use in the attempt above but when I check the jquery.active in my success method it is "1" and not 0 even though only one button click has been made.

I also checked this post which got me thinking of jquery.active above but alos $.ajaxStart and $.ajaxStopp.

The problem with $.ajaxStart and $.ajaxStopp and far as I understand is that they are global and I want specific code to execute when these alarms are signed and don't wish for this to happen on every page when an ajax is made.

How do I manage this?

Community
  • 1
  • 1
ThunD3eR
  • 3,216
  • 5
  • 50
  • 94
  • you want to track the AJAX calls or you want execute some code only after the list of calls are completed?? – Aravind Sep 12 '16 at 09:18
  • i want to execute script when all ajax are cmpleated in this scope. With that in mind these request are not dependent on eacother. i simply want to know if the browser is running any ajax requests when I come back to my success method. If there are ajax request still running (user clicked on yet another button) then do nothing, else execute script – ThunD3eR Sep 12 '16 at 09:42
  • related post: https://stackoverflow.com/q/5680537/470749 – Ryan May 12 '21 at 20:59

3 Answers3

0

After a great deal of pondering and searching for some kind of build in function in jquery i decided to make an own attempt.

What I wanted:

  1. Make several ajax requests
  2. Keep track of the amount of request that I had in a particular scope(NOT GLOBAL)
  3. execute script when no ajax are being made.

code:

global array:

 ajaxRequests: { value: [] }

before each ajax request:

$.automation.globals.ajaxRequests.value.push(1);

after each ajax request:

    clearAjax: function() {
        $.automation.globals.ajaxRequests.value.splice(-1, 1);
    }

summing it up:

       $(".signAlarm")
            .on("click",
                function () {
                    var _this = $(this).parents(".alarmRow");
                    var alarm = {
                        Id: $(_this).data("id")
                    }

                    $.automation.globals.ajaxRequests.value.push(1);

                    $.automation.worker.postJson("/Alarm/SigAlarm",
                    JSON.stringify({ alarm }),
                    function (data) {
                        $.automation.worker.clearAjax();
                        if ($.automation.globals.ajaxRequests.value.length === 0) {
                           // all ajax finished, execute code
                        }
                        $(_this).remove();
                    });
                });
ThunD3eR
  • 3,216
  • 5
  • 50
  • 94
0

You can use deferred objects.

$('.signAlarm').each(function() {
    var prom = $.Deferred().resolve();
    $(this).click(function() {
        var _this = $(this).parents(".alarmRow");
        var alarm = {
            Id: $(_this).data("id")
        };
        prom = prom.then(
            function () {
                return $.post({
                    'url': '/Alarm/SigAlarm',
                    'data': JSON.stringify(alarm),
                    'contentType': 'application/json' // assuming you want the server to think you're sending json
                });
            }
        ).done(function () {
            if (prom.state() === "resolved") {
                // all ajax finished, execute code
            }
            $(_this).remove();
        });
    });
});

I'm not sure what the $.automation is for but I'll edit my answer if you needed it. Also, note how i use .each() to create a scope so that each element with class signAlarm is treated individually. You could create a global prom variable if you wanted all calls for all clickable elements to share.

-1

use async property of ajax.

async (default: true) Type: Boolean

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

refer this

$.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //set this false
            success: function() {}
        });
Santhosh Nayak
  • 2,312
  • 3
  • 35
  • 65
  • All calls are to be executed asynchronously and are not dependant on eachother. I need to know if the browser is executing any ajax requests when I am in the success method of a current call. So when you click a button, you return to success method but before that the user managed to click a new button and start yet another ajax, in the first success method I want to know if any other ajax request are pending – ThunD3eR Sep 12 '16 at 09:44