jQuery ajax call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?

Michael picture Michael · Feb 17, 2011 · Viewed 7.1k times · Source

I have a situation where on page unload I am firing a request to delete the draft of a user's work. This works fine until a user chooses to refresh the page, whereupon inspecting Chrome's network tab shows that Chrome is loading the new page before the ajax request is actually fired. The result is a new draft is created by the page load, and then deleted right away by the ajax call. Here is basically what I'm doing:

window.onbeforeunload = function(){
    if (pageUpdated){
        return 'Are you sure you want to abandon this draft?';
    }
}

window.onunload = function(){
    $.ajax({
        async: false,
        type: 'DELETE',
        url: '/some/url/'
    });
}

Is there a way to force the onunload handler to complete before the request for the new page is sent?

Browsers Tested: (Chrome 9, FF 3.6) on Ubuntu 10.04 Lucid

Answer

Silkster picture Silkster · Aug 12, 2011

In onbeforeunload or $.unload() set up your AJAX object with async = false. This will make sure the ajax call completes before the page is unloaded.

I know this question is a few months old, but I wanted to add this info in case it helps anyone searching for a similar issue with AJAX!