I want to make an AJAX call before the user leaves the page (so basically before leaving the page and before refreshing the page)?
How can this be done. I was trying to search something with jQuery but didnt get anything.
I tried to use the following code -
window.onbeforeunload(function(){alert('before unload');});
But the alert box never appears when leaving the page(closing the browser tab) or refre开发者_JAVA百科shing the page.
How can this be accomplished?
You should try unload() from jquery:
$(window).unload(function(){
//Do your call
alert('before unload');
});
oro you could use the beforeunload event. You should test it well because browser tend to imlement those things differently. taken from jquery documentation:
The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.
$(window).unload(function() {
alert('Visitor left page');
});
Regarding the ajax call, you can do it, but you must set the async
to false
.
$.ajax({
async: false,
...
});
Your code is simply wrong. The unbeforeunload is used to ask the person if he really want to leave the page. You need unload.
window.onunload = function() {
// Make your AJAX call
}
Better use jQuery.unload() method
精彩评论