Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort ajax request on page refresh

I have a form, on submit of that I am making an ajax request which is sometimes taking time to get the request, so what I am trying to do is whenever user refresh or clicks back button of the browser after form submitting i want to abort that ajax call

  • What I am doing is

    $("#formId").submit(function(event) {
       event.preventDefault();
       var xhr = $.ajax({
          url : "Drilldown",
          method : "GET",
          success : function(data) {
             //  here doing ,my stuff    
          },
          complete : function() {
             $('.loader').hide();
             $('.overlay').hide();
          }
      });    
      window.onbeforeunload = function() {
         return "some message"; // here when user clicks on leave then want to abort like `xhr.abort`
      };    
    });
    
  • whenever the user clicks on leave I want to abort my ajax request

How can I do that?

**I specifically want to do that when ever form submit and once form is submitted,i want to abort that function also onbeforeunload **


1 Answers

You can directly xhr.abort() in "onbeforeunload" event handler method:

// Define xhr variable outside so all functions can have access to it
var xhr = null;

$("#formId").submit(function(event) {
    event.preventDefault();
    xhr = $.ajax({
        url: "Drilldown",
        method: "GET",
        success: function(data) {
            //  here doing ,my stuff

        },
        complete: function() {
            $('.loader').hide();
            $('.overlay').hide();
        }
    });
});

window.onbeforeunload = onUnload;

function onUnload() {
    if(xhr) xhr.abort();
    return "some message";
};
like image 101
RK_15 Avatar answered Dec 23 '25 11:12

RK_15