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

淺唱寂寞╮ 提交于 2019-12-01 21:28:57

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!

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.

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");
});

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!