Search code examples
javascriptjqueryajaxonbeforeunload

jQuery unload with an AJAX call not working in Chrome


This is my very simple code snippet:

$(window).unload(function() {
        $.ajax({
            url: 'stats_pages.php?last_id='+$("#last_id").val(),
        });
});

Simple enough. The AJAX call gets called perfectly in Firefox, but fails in Chrome. I've tried other variations, which sort of work:

window.onbeforeunload = function(){
        $.ajax({
            url: 'stats_pages.php?last_id='+$("#last_id").val(),
        });
        return false;
}

This works in Chrome, but it alerts "false" with the usual "Are you sure you want to leave this page?" message, which is not what I want obviously. Without the return false;, it doesn't fire the AJAX call.

Ideally I like the first solution the best, but does anybody know what's going on?


Solution

  • Set ASYNC : false in your ajax call

    $(window).unload(function() {
            $.ajax({
                url: 'stats_pages.php?last_id='+$("#last_id").val(),
                async : false,
            });
    });