2

Consider this code that runs when the page is loaded:

if ($('#content-recommendation').length) {
    $.ajax({
    url:'/get_content_recommendation/' + gon.item_id + '.js',
    type:"get"
  });
}

And this request take about 15 seconds to complete in development. If I go to another page I have to wait until the Ajax is completed so, how do I cancel that Ajax request?

Vitor Vezani
  • 846
  • 2
  • 8
  • 24

2 Answers2

1

You can use the abort() method to abort the request - but be aware that it will just abort the client side listeners from being executed, the server side processes initialized by the quest will still be running

//in a shared scope
var xhr;

//then
if ($('#content-recommendation').length) {
    xhr = $.ajax({
        url: '/get_content_recommendation/' + gon.item_id + '.js',
        type: "get"
    }).always(function () {
        xhr = undefined;
    });
}

//later before moving to the new page
if (xhr && xhr.readyState != 4) {
    xhr.abort();
}

How to cancel/abort jQuery AJAX request?

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can use abort() to cancel the current request. Detailed instructions here How to cancel/abort jQuery AJAX request?

Community
  • 1
  • 1
Ruy Rocha
  • 894
  • 8
  • 8