最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to execute ajax function onbeforeunload? - Stack Overflow

programmeradmin2浏览0评论

I'm developing a php/javascript chat.

When the user logs in, his/her username is inserted in a MySQL table called queue. This insert returns the mysql_insert_id() that will be stored in a session variable called $_SESSION['CHAT_QUEUE_ID']

I need the MySQL table row to be deleted when the user closes the page.

I tried the following, but without success:

js file

window.onbeforeunload = closeSession;
function closeSession(){
    $.ajax({
        url: "/chat/process/chat.php",
        type: "GET"
    });
    return "disconnected";
}

chat.php

$delete= "DELETE FROM queue WHERE id = " . $_SESSION['CHAT_QUEUE_ID'];
// query, etc

Is there any way to do this?

I'm developing a php/javascript chat.

When the user logs in, his/her username is inserted in a MySQL table called queue. This insert returns the mysql_insert_id() that will be stored in a session variable called $_SESSION['CHAT_QUEUE_ID']

I need the MySQL table row to be deleted when the user closes the page.

I tried the following, but without success:

js file

window.onbeforeunload = closeSession;
function closeSession(){
    $.ajax({
        url: "/chat/process/chat.php",
        type: "GET"
    });
    return "disconnected";
}

chat.php

$delete= "DELETE FROM queue WHERE id = " . $_SESSION['CHAT_QUEUE_ID'];
// query, etc

Is there any way to do this?

Share Improve this question edited Dec 5, 2012 at 15:09 Jeff Yates 62.4k20 gold badges142 silver badges192 bronze badges asked Mar 14, 2012 at 12:12 matheusvmbrunomatheusvmbruno 2,3003 gold badges16 silver badges20 bronze badges 3
  • 3 Are you aware that browser support for onbeforeunload is limited? E.g. opera doesn't support it. – ckruse Commented Mar 14, 2012 at 12:17
  • I had not thought of that. any suggestion? – matheusvmbruno Commented Mar 14, 2012 at 12:50
  • 2 The common method is to define a timeout. If a user hadn't had an activity for a specific amount of time he is disconnected. – ckruse Commented Mar 14, 2012 at 12:52
Add a comment  | 

1 Answer 1

Reset to default 21

You fire your ajax async (default for jquery - ajax). But the browser won't wait for anything on unload.

try setting async : false in the ajax-settings. But you can never be sure that this will work in all browsers everytime.

see the comment here: http://api.jquery.com/unload/#dsq-comment-body-132164390

发布评论

评论列表(0)

  1. 暂无评论