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

4

3

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

Acquittal answered 17/2, 2011 at 20:27 Comment(1)
Does this only occur in Chrome? Or does it also occur in FF, IE, Safari?Perique
M
4

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!

Muriah answered 12/8, 2011 at 15:19 Comment(0)
A
3

Making the XHR request synchronous should delay the loading of the new page until after the request is complete. I don't know how jQuery runs its synchronous XHR requests under the hood, but here's how you can do it using plain JavaScript:

var request = new XMLHttpRequest();
// or new ActiveXObject("Microsoft.XMLHTTP") for some versions of IE
request.open("GET", "/some/url", false);
request.send(null);

var result = request.responseText;
alert(result);

Putting that in your unload handler should make the browser wait until "/some/url" is loaded before it moves on to the next page.

Adoptive answered 22/5, 2011 at 2:58 Comment(0)
D
3

I'm here to confirm @Silkster answer. I can fire an AJAX request after set an option async = false

Here is the example code.

$(window).unload( function () {
    $.ajaxSetup ({
        async: false  
    });
    $.get("target.php");
});
Dong answered 19/9, 2012 at 12:36 Comment(0)
P
1

You can try using window.onbeforeunload instead, though I'm not sure if it's implemented in all browsers.

Perique answered 17/2, 2011 at 20:31 Comment(1)
I'm already using onbeforeunload for a confirmation. Edited code to reflect that. Thanks!Acquittal

© 2022 - 2024 — McMap. All rights reserved.