Search code examples
jquerypage-refresh

stop refreshing the page in the event "unload"


How to stop updating the page in the event unload?

$(window).unload(function(){
    if(confirm('Do you really want to exit the survey without completing it? Your data will be deleted.') ){
         // This does not currently work in the method 
         //  onbeforeunload which took Nick Craver
            $.ajax({
                url: 'db_sotr_file.anket_my.ajax_remove_anketa',
                dataType: 'html',
                success: function(){
                    $.cookie('refresh_page', null);
                    $.cookie('hashid', null);
                    $.cookie('sessionid', null);
                }
            });            // This moment is the most important 

         // page the refresh
         return true;
    }
    // don't refresh the page
    return false;
});

Solution

  • You need to return the string and bind directly, like this:

    window.onbeforeunload = function() {
      return 'Do you really want to exit the survey without completing it? Your data will be deleted.';
    };
    

    To be reliable, you need onbeforeunload instead...and jQuery doesn't bind to this correctly cross-browser, so it's better to set an event handler directly. Some browsers won't allow logic in there other than a return "string" as far as stopping the page goes...so use that format to work cross browser (Firefox mainly here).