Send AJAX to server beforeunload [duplicate]

Asked
Active3 hr before
Viewed126 times

9 Answers

server
90%

When you refresh (or close)your browser, beforeunload is being called. And it means as soon as beforeunload is finished executing, page will refresh (or close).,success of ajax is supposed to be called after few secs, but you dont see it as page has been refreshed / closed.,So supposedly starting at Firefox > 4, binding the window jQuery object to beforeunload doesn't work anymore.,When you do an ajax request, (since its asynchronous) javascript interpreter does not wait for ajax success event to be executed and moves down finishing the execution of beforeunload.

Just for sake of completion, here's what I did, thanks to @Jashwant for the guidance: I noticed that this other SO Q&A suggested the same solution. The KEY is the async:true(false) in the $.ajax call below:

$(window).bind('beforeunload', function() {
   if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
      console.log('firefox delete');
      var data = {
         async: false
      };
      memcacheDelete(data);
      return null;
   } else {
      console.log('NON-firefox delete');
      var data = {
         async: true
      };
      memcacheDelete(data);
      return null;
   }
});

function memcacheDelete(data) {
   $.ajax({
      url: "/memcache/delete",
      type: "post",
      data: {},
      async: data.async,
      success: function() {
         console.log('memcache deleted');
      } //success
   }); //ajax
}
88%

So supposedly starting at Firefox > 4, binding the window jQuery object to beforeunload doesn't work anymore.,When you do an ajax request, (since its asynchronous) javascript interpreter does not wait for ajax success event to be executed and moves down finishing the execution of beforeunload. ,I realize it is bad to do browser sniffing and that there is no difference between what's included in the if and else statements. I'm merely showing code for what I've tried unsuccessfully in Firefox.,When you refresh (or close)your browser, beforeunload is being called. And it means as soon as beforeunload is finished executing, page will refresh (or close).

Anyone have any ideas?

$(window).bind('beforeunload', function() {
   if (/Firefox[/s](d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
      console.log('firefox delete');
      memcacheDelete();
      return null;
   } else {
      console.log('NON-firefox delete');
      memcacheDelete();
      return null;
   }
});

function memcacheDelete() {
   $.ajax({
      url: "/memcache/delete",
      type: "post",
      data: {},
      success: function() {
         console.log('memcache deleted');
      } //success
   }); //ajax
}
load more v
72%

So supposedly starting at Firefox > 4, binding the window jQuery object to beforeunload doesn't work anymore.,What'd I'd like to do is submit an AJAX post to delete my server's memcache data.,When you do an ajax request, (since its asynchronous) javascript interpreter does not wait for ajax success event to be executed and moves down finishing the execution of beforeunload. ,I realize it is bad to do browser sniffing and that there is no difference between what's included in the if and else statements. I'm merely showing code for what I've tried unsuccessfully in Firefox.

Anyone have any ideas?

$(window).bind('beforeunload', function() {
   if (/Firefox[/s](d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
      console.log('firefox delete');
      memcacheDelete();
      return null;
   } else {
      console.log('NON-firefox delete');
      memcacheDelete();
      return null;
   }
});

function memcacheDelete() {
   $.ajax({
      url: "/memcache/delete",
      type: "post",
      data: {},
      success: function() {
         console.log('memcache deleted');
      } //success
   }); //ajax
}
load more v
65%

All that said, beforeunload isn't the right place to be sending network requests, synchronous or not.,The HTML Standard says that beforeunload is there "in case the page would like to show a warning prompt".,My understanding is when unlock function calls on window close. function should send xhr request to server after that browser tab should be closed. In my case i don't need the response of xhr call.,It isn't meant for doing (possibly long-running) asynchronous tasks like sending network requests.

// binding beforunload event

componentDidMount() {
   if (window.addEventListener) {
      window.addEventListener('beforeunload', this.onUnload, false);
   } else if (window.attachEvent) {
      window.attachEvent('onbeforeunload', this.onUnload);
   }
}

// call api function 'unlock'
onUnload() {
   unlock();
}

// api 
export function unlock(Id) {
   return axios
      .get(UNLOCK(Id))
      .then((data) => data);
}
load more v
75%

If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.,Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question. ,Understand that English isn't everyone's first language so be lenient of bad spelling and grammar., communitylounge Who's Who Most Valuable Professionals The Lounge   Where I Am: Member Photos The Insider News The Weird & The Wonderful

window.onbeforeunload
<script>
        window.onbeforeunload = function (evt) {
            /* get the scenario id first. */
            var id1 = document.getElementById("<%= hdScenario1.ClientID %>").value;
            var id_1='';

            $.ajax({
                type: "POST",
                url: "scenarioAdd.aspx/CheckUpdateScenario",
                data: '{scenarioId: ' + id1 + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    id_1 = response.d;

                    if (id_1 == 0) {
                        var message = 'Save it before you close.';

                        if (typeof evt == 'undefined') {
                            evt = window.event;
                        }
                        if (evt) {
                            evt.returnValue = message;
                        }
                        return message;
                    }
                },
                failure: function (response) {
                    alert(response.d + " f");
                    id_1 = "0";
                },
                error: function (response) {
                    alert(response.d + " e");
                    id_1 = "0";
                }
            });

            // leave page code was before here.
        }
    </script>
var message = & #39;Save it before you close.&# 39;;

if (typeof evt == & #39;undefined&# 39;) {
   evt = window.event;
}
if (evt) {
   evt.returnValue = message;
}
return message;
load more v
40%

From https://usefulangle.com/post/62/javascript-send-data-to-server-on-page-e... : ,The problem with sending an asynchronous AJAX inside the unload event is that the browser may abort the AJAX request when the document is being unloaded. The AJAX request is send, but it is aborted later.,oh yes right, because it is an asynchronous call :) ,From the same post I see also a suggestion that we might send a synchronous AJAX request, which will block the user, but will ensure the input is autosaved and no errors will occur.

Maybe something like this :

triggerAjaxSubmitWithoutProgressIndication(ajax_class) {
   ....
   // We expect the method to be aborted by the browser as this an asynchronous 
   // AJAX call during the unload event and therefore we remove the error handling 
   // in order to prevent errors from being thrown.
   if(Drupal.autosaveForm.beforeUnloadCalled) {
         ajax_error = ajax.error;
         ajax.error = function() {}
      }
      ....
   ajax.error = ajax_error;
}
load more v
22%

Users are so annoying! There they go, leaving the page before we can save the data to the API. Back in the old days, we would attach a window.unload handler and try to send an AJAX request, but this was slow and unreliable.,The Beacon provides a reliable way to send a small amount of data after the page has been unloaded. It’s not bound to the lifetime of the page and it doesn’t slow down the user.,We call sendBeacon with the URL and the text string to be sent. The browser handles the rest. We still want to attach our call to sendBeacon to the window unload event, so that we queue our data to be sent as the page is closing., Request Metrics is the simplest, fastest, and most affordable way to monitor your website performance. We're bringing fast websites back for everyone.

(function client() {
   if (!navigator.sendBeacon) {
      return;
   }

   function onUnload() {
      var data = {
         "foo": "bar"
      };
      var text = JSON.stringify(data);

      navigator.sendBeacon("http://api.yourservice.com/beacon", text);
   }

   window.addEventListener("unload", onUnload);
})();
load more v
60%

Telerik and Kendo UI are part of Progress product portfolio. Progress is the leading provider of application development and digital experience technologies.,Can you please verify that on your machine? Any further details regarding your particular configuration settings can help us determine the reason for the abnormality and address it asap. Best regards,,Hello Jon, This is indeed odd since the onbeforeunload browser event should be raised only when you attempt to close the browser window. I performed a quick test under IE/FF using the latest version of RadControls for ASP.NET AJAX and the event was not fired on ajax requests. Here is the code I used: ,All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with:

load more v
48%

If you are using a previous version of the snippet, it is highly recommended that you update to the latest version so that you will receive these previously unreported issues.,Download via CDN scenario: Update the code snippet that you currently use to point to the following URL:,Only use one method to add the JavaScript SDK to your application. If you use the NPM Setup, don't use the Snippet and vice versa.,Correlation context (if any) where request is made

Download via CDN scenario: Update the code snippet that you currently use to point to the following URL:

"https://js.monitor.azure.com/scripts/b/ai.2.min.js"
load more v

Other "server-undefined" queries related to "Send AJAX to server beforeunload [duplicate]"