$ (window) .unload does not work as expected

I am creating a small chat application with PHP + MySQL + JavaScript, I have written the disonnectUser () function, which is called when the user clicks the disconnect button. There he is:

function disconnectUser(){
            $.post('web/WEB-INF/classes/handleChatUser.php',{ action: 'disconnect',nick: localNickname});           
            $('#chat').stop(true,true).fadeOut(2000,function(){
                nicknameDialog();
            });

            $('#messageInput').val(null);
            $('#clientList').html(null);
            $('#chatScreen').html(null);
            clearInterval(refreshIntervalId);
            clearInterval(refreshIntervalId2);
            connected = false;
        }

And it works like a charm, but when I call this function in a different context, when the user, instead of clicking, disables only the exit from the page, in this function

$(window).unload(function() {
                if(connected){
                disconnectUser();
                connected = false;
                }
            });

he does not work. And I am sure that this is caused, because if I set a warning, it was usually called before closing the page. I think the page closes before the code runs completely, so I think that if I put some block there until the code finishes working, will it work?

+3
source share
3 answers

, beforeunload?

window.onbeforeunload = function() {
    if(connected){
        disconnectUser();
        connected = false;
    }
};

, disconnectUser connected false, .

, jQuery beforeunload, JS, :

http://groups.google.com/group/jquery-en/browse_thread/thread/4e5b25fa1ff5e5ee?pli=1

+2

, $(window).unload() AJAX ( , AJAX is assync).

AJAX, .. . disconnectUser:

$.ajax({
    type: 'POST',
    async: false, // This is the guy.
    url: '/blablabla'
});

: $(window).unload AJAX- -

+6

Try using a synchronous query. Perhaps combined with onbeforunload, like the proposed other poster. If that doesn't work, I guess you're out of luck. A synchronization request blocks the browser when this happens, so you can use it only for the unload function, assuming the method even works.

function disconnectUser(){
            jQuery.ajax({
                url: 'web/WEB-INF/classes/handleChatUser.php',
                data: { action: 'disconnect',nick: localNickname},
                type: 'POST',
                async: false
            });

            $('#chat').stop(true,true).fadeOut(2000,function(){
                nicknameDialog();
            });

            $('#messageInput').val(null);
            $('#clientList').html(null);
            $('#chatScreen').html(null);
            clearInterval(refreshIntervalId);
            clearInterval(refreshIntervalId2);
            connected = false;
        }
+1
source

All Articles