Send AJAX to server beforeunload [duplicate]
Solution 1:
Ajax is asynchronous.
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).
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
.
success
of ajax is supposed to be called after few secs, but you dont see it as page has been refreshed / closed.
Side note:
.success()
method is deprecated and is replaced by the .done()
method
Reference
Solution 2:
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
}