0

Scenario: I have a web application which makes various ajax requests. Some of these occur due to user interaction (e.g. clicking a row inside a table, which runs an ajax request to update further details inside the row). Others are "background tasks" (e.g. checking whether there are new downloads available).

The user must be logged in to my application to perform any functionality; therefore any ajax request will fail if the user is logged out.

So the ajax requests might be something like this:

  • /click-table-row
  • /check-downloads
  • /some-other-functionality
  • ...

I have added the following to a global .js file:

$(function() {

$( document ).ajaxError(function() {
    swal({
        position: 'top-end',
        toast: true,
        title: 'Network error',
        html: 'Please try again. If problem persists please login again.',
        type: 'error',
        confirmButtonText: 'Close'
    });
});

});

This is using SweetAlert (swal) to show a message if any of the ajax requests fail by utilising jquery's ajaxError.

If I simulate ajax request failure - by running my logout script in a separate browser tab - and then have the application make ajax requests, it will execute the code inside ajaxError each time an ajax request is made (which might be a background task trying to run, or the user trying to interact with the application). For example if there are 3 requests as shown in the list at the top of the question, it will execute the swal code 3 times. I assume this is technically correct because 3 ajax requests have indeed failed.

What I'm trying to do is work out a way to implement: "if the first ajax request fails, stop running the code inside ajaxError() again".

I don't know if or how this is achievable? Please can someone advise.

jquery 3.2.1, SweetAlert 2

Andy
  • 5,142
  • 11
  • 58
  • 131
  • [Disabling some jQuery global Ajax event handlers for a request](https://stackoverflow.com/questions/7436195/disabling-some-jquery-global-ajax-event-handlers-for-a-request) this might help you – Ulug Toprak Jan 08 '19 at 10:38

1 Answers1

0

check StatusCode=> 401

$(document).ajaxError(function(e, xhr) {
if(xhr.status===401)
    {
    swal({
         position: 'top-end',
         toast: true,
         title: 'Network error',
         html: 'Please try again. If problem persists please login again.',
         type: 'error',
         confirmButtonText: 'Close'
        });
    }

});

MAjidH1
  • 121
  • 4