Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(window).unload not working as expected

I'm making a small chat application with PHP + MySQL + JavaScript, I've written a function disonnectUser(), which is called when the user press the disconnect button. Here it 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 very function in another context, when the user instead of pressing disconnect just exit the page, in this function

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

it doesn't work. And I'm sure it's being called, because if I put an alert it's called normally before closing the page. I think the page is closing before the code runs completely, so I think if I put some block there until the code finish running it would work?

like image 452
Rodrigo Cavalcante Avatar asked Jun 30 '26 13:06

Rodrigo Cavalcante


2 Answers

The problem is that $(window).unload() doesn't waits any AJAX call before closing the window (what is right because AJAX is assync).

You need to force the AJAX to be sync, ie, wait the response. Inside your disconnectUser function:

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

You can read more about it here: $(window).unload wait for AJAX call to finish before leaving a webpage

like image 79
Erick Petrucelli Avatar answered Jul 03 '26 03:07

Erick Petrucelli


Instead of unload, how about beforeunload?

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

Also, your disconnectUser method already sets connected to false, no need to do it here also.

It also seems that jQuery doesn't really handle the beforeunload event, which is why you'll need to revert to native JS to handle this:

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

like image 22
Eli Avatar answered Jul 03 '26 03:07

Eli