Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

javascript - PHP update database on close window

I am trying to update the database when the user close or refresh the browser. This is my code:

$(window).bind('unload', function(){
    $.ajax({
        type: 'get',
        async: false,
        url: 'liberaLugar.php?idCurso=2'
    });
});

Any help will be appreciated. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should work for you in most cases. of course, if your server is unreachable, you could freeze the browser, so we should also add a timeout. it may also be helpul to give your user some visual indicator of what the hell is going on, so we should set the cursor to waiting.

var unloaded = false;
$(window).on('beforeunload', unload);
$(window).on('unload', unload);  
function unload(){      
    if(!unloaded){
        $('body').css('cursor','wait');
        $.ajax({
            type: 'get',
            async: false,
            url: 'liberaLugar.php?idCurso=2',
            success:function(){ 
                unloaded = true; 
                $('body').css('cursor','default');
            },
            timeout: 5000
        });
    }
}

EDIT: Synchronous AJAX is now deprecated in Webkit Browsers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...