How to execute ajax function onbeforeunload?
Asked Answered
R

1

12

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?

Rosales answered 14/3, 2012 at 12:12 Comment(3)
Are you aware that browser support for onbeforeunload is limited? E.g. opera doesn't support it.Dairy
I had not thought of that. any suggestion?Rosales
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.Dairy
M
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

Maxia answered 14/3, 2012 at 12:21 Comment(4)
It works perfectly. should have thought of that before... THANKS!Rosales
Also - if you are triggering the same functional ajax call that you use asynchronously (or a number of ajax calls) you can set them to async globally in your onbeforeunload statement: $.ajaxSetup({ async: false });Subcelestial
A useful followup on setting async=false to reset to async=true: https://mcmap.net/q/405823/-way-to-know-if-user-clicked-cancel-on-a-javascript-onbeforeunload-dialogHolmgren
Do you know why we have to set it to be synchronous ? As what we want is to send data to the server but don't care about server response since the data is passed ?Crenelate

© 2022 - 2024 — McMap. All rights reserved.