1

My first issue was that I was looking for a way to automatically abort an AJAX request if the user navigated away from a page while the request was being made. I found this helpful solution which solved that problem. Now my issue is that upon aborting specific AJAX requests within my application, the user is directed to an error page (I believe this is the behavior intended in some of the error callbacks) and I do not want that to be the behavior in the case when the user simply just navigated to a different page during the request.

What i'm hoping to do is continue using the solution linked above, but modify it in a way that will prevent the execution of the error callback. I understand that I can check for the status and readystate properties inside of an error callback, but this would mean I would have to include these checks in all of my AJAX requests across my application and that just isn't very maintainable. My goal is to have this logic all in one place or at least in as few places as possible.

I've tried the following with no luck. It appears that the local error callback is executed first, and then execution proceeds to the global handler and by then its too late.

Any help is greatly appreciated. Thank you

function onPageLoaded() {
    var jqxhrs = [];

    $(window).bind("beforeunload", function (event) {
        $.each(jqxhrs, function (idx, jqxhr) {
            if (jqxhr) {
                jqxhr.abort();
            }
        });
    });

    $(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError) {
        if (jqXHR.status === 0 || jqXHR.readyState === 0) {
            return;
        }
    });

    function registerJqxhr(event, jqxhr, settings) {
        jqxhrs.push(jqxhr);
    }

    function unregisterJqxhr(event, jqxhr, settings) {
        var idx = $.inArray(jqxhr, jqxhrs);
        jqxhrs.splice(idx, 1);
    }

    $(document).ajaxSend(registerJqxhr);
    $(document).ajaxComplete(unregisterJqxhr);
}

1 Answers1

0

you can try this somewhere in your code

   var response=Promise.all([ajaxcall1,ajaxcall2,ajaxcall3,....])

if one of this promises is not resolved so you can handle the error

response.then((resp)=> //your code to handle resp )
.catch ((error)=>{ //handle error here})
Sven.hig
  • 4,449
  • 2
  • 8
  • 18