Send AJAX to the server before downloading

So, presumably starting in Firefox> 4, binding a window to a jQuery object before beforeunload no longer works.

What I would like to do is send an AJAX message to delete memcache server data.

When I update the only open tab, I see that the beforeunload event is beforeunload in both firefox and chrome with the following code, as evidenced by the console.log message, "firefox / NON-firefox delete". The problem is that I never see the console.log message "memcache delete" indicating that my server has never seen the $.ajax request.

I understand that working with browning is bad and that there is no difference between what is included in the if and else statements. I am just showing the code for what I tried unsuccessfully in Firefox.

Does anyone have any idea?

 $(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 } 
+8
javascript jquery cross-browser onbeforeunload
source share
2 answers

Ajax is asynchronous.

When you refresh (or close) the browser, beforeunload is beforeunload . And this means that as soon as beforeunload finishes executing, the page will beforeunload (or close).

When you execute an ajax request, (since it is asynchronous), the javascript interpreter does not wait for the ajax success event to complete and proceeds to complete the execution of beforeunload .

success ajax is supposed to be called in a few seconds, but you do not see it, because the page has been updated / closed.

Side note:

.success() method is deprecated and is replaced by the .done() method

Link

+11
source share

Just for the sake of completion, here's what I did, thanks to @Jashwant for the guide: I noticed that this other SO Q & A offered the same solution . The KEY is 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 } 
+7
source share

All Articles