8

In my application, there's an object that needs to be ajaxed back to the server before the user switches to another page or closes his browser.

For the moment, I'm using something like this:

$(window).on('unload', function () {
    $.ajax(....);       
});

Will the ajax call fire in all browsers or are there situations where this will not work and where this situation needs to be handled differently? I don't need to deal with anything in terms of a success function, I'm only concerned about the information making it to the server.

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 1
    You can't rely on an "unload" event being generated before a page goes away. It'll be done by the browser in *normal* circumstances, but not when the browser can't do anything about it (sudden system shutdown, for example). – Pointy Oct 09 '13 at 14:15
  • You can't rely on anything by that logi... *pulls power chord* – Stijn de Witt Jul 24 '15 at 11:19

4 Answers4

5

If you're using jQuery, you can set async to false in the ajax call. And it might work, but your results may vary by browser. Here's a jsFiddle example. http://jsfiddle.net/jtaylor/wRkZr/4/

// Note:  I came across a couple articles saying we may should to use window.onbeforeunload instead of or in addition to jQuery's unload.  Keep an eye on this.
//        http://vidasp.net/jQuery-unload.html
//        https://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery

var doAjaxBeforeUnloadEnabled = true; // We hook into window.onbeforeunload and bind some jQuery events to confirmBeforeUnload.  This variable is used to prevent us from showing both messages during a single event.


var doAjaxBeforeUnload = function (evt) {
    if (!doAjaxBeforeUnloadEnabled) {
        return;
    }
    doAjaxBeforeUnloadEnabled = false;
    jQuery.ajax({
        url: "/",
        success: function (a) {
            console.debug("Ajax call finished");
        },
        async: false /* Not recommended.  This is the dangerous part.  Your mileage may vary. */
    });
}

$(document).ready(function () {
    window.onbeforeunload = doAjaxBeforeUnload;
    $(window).unload(doAjaxBeforeUnload);
});

In Google Chrome, the ajax call always completes before I navigate away from the page.

However, I would VERY MUCH NOT RECOMMEND going that route. The "a" in ajax is for "asynchronous", and if you try to force to act like a synchronous call, you're asking for trouble. That trouble usually manifests as freezing the browser -- which might happen if the ajax call took a long time.

If viable, consider prompting the user before navigating away from the page if the page has data that needs to be posted via ajax. For an example, see this question: jquery prompt to save data onbeforeunload

Community
  • 1
  • 1
Jamey
  • 1,595
  • 9
  • 23
1

No, unfortunatelly your Ajax call will not get completed as the document will unload during the async call. You cannot do many things when the user closes the window.

George Mavritsakis
  • 6,829
  • 2
  • 35
  • 42
1

Instead of doing an ajax sync call (deprecated on latest browsers and can get exception), you can open a popup:

$(window).on('unload', function () {
    window.open("myscript.php");
});

You can add obviously parameters to the link and you can automatically close the popup if you like. Popup blocker must be disactivated for your domain in the browser options.

Fil
  • 1,032
  • 13
  • 29
0

You have to use the onbeforeunload event and make a synchronous AJAX call.

$.ajax({
    ...
    "url": "http://www.example.com",
    "async": false,
    ...
});
Butt4cak3
  • 2,389
  • 15
  • 15