0

I have a jQuery each loop with an ajax function inside but I'm experiencing an issue when trying to navigate away from this page while the loop is still running, basically I can't navigate to any other page unless the each loop has finished.

I don't need this loop to finish because it's basically only needed as a visual indicator, its far from being so important to sacrifice user experience for.

    $.each( get_link, function( i, val ) {

    $(window).on("beforeunload", function() {
        return false;
    });

    $.ajax({
        type: "POST",
        url: url,
        async: true,
        data: {url: val},
        success: function(data)
        {
            let row = $("#status[data-url='" + val + "']");
            row.html(data);
            $("#loader[data-url='" + val + "']").removeClass("loader vertical-align-middle loader-bounce");
        }
    });
});

As you can see I have tried to fix it with $(window).on("beforeunload") but beforeunload creates an unnecessary alert window which unfortunately I couldn't find a way to disable.

EDIT: The above code isn't breaking the loop either...

Is beforeunload a good idea? Maybe there are better approaches to break a loop on page exit?

f.khantsis suggested to abort the ajax operation which is a good idea but it doesn't help because I run an each loop on an array with 5-6 keys. So if one of them is aborted the loop just goes on to run with all the remaining keys.

Ricardo
  • 1,653
  • 8
  • 26
  • 51
  • your beforeunload doesn't do anything, since it just returns false from the listener. – f.khantsis Apr 22 '19 at 17:08
  • The thing is, it works. As soon as the alert appears everything else is not loading anymore as if the loop was stopped. Edit: You are right, it stops the loop until I confirm. Then I wait till the loop finishes :( – Ricardo Apr 22 '19 at 17:09

2 Answers2

0

see Abort Ajax requests using jQuery

Basically, jQuery.ajax returns a jqXHR object, which can be used to abort a pending request.

$.each( get_link, function( i, val ) {

    var xhr = $.ajax({
      type: "POST",
      url: url,
      async: true,
      data: {url: val},
      success: function(data)
      {
          let row = $("#status[data-url='" + val + "']");
          row.html(data);
          $("#loader[data-url='" + val + "']").removeClass("loader vertical-align-middle loader-bounce");
      }
    });
    $(window).on("beforeunload", function() {
      xhr.abort();
    });
});
f.khantsis
  • 3,256
  • 5
  • 50
  • 67
0

$(window).on("beforeunload") should probably be outside your loop.

Then it can set a global variable which you would then check for in your loop, something like:

var leavingThePage = false;

$(window).on("beforeunload", function() {
        leavingThePage = true;
});

$.each( get_link, function( i, val ) {
    if (leavingThePage)
        return false;

    $.ajax({
      ... Do ajax stuff ...
    });
});
Wolm
  • 16
  • 3