Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX and user leaving a page

I'm working on a chat and I'm trying to figure out how I can detect that the user has left the page or not. Almost everything is being handled by the database to avoid the front end from messing up.

So what I'm trying to do is once the page is left for any reason (window closed, going to another page, clicking a link, etc.) an ajax call will be fired before a person leaves so I can update the database.

This is what I've tried:

$(window).unload(function(){
      $.post("script.php",{key_leave:"289583002"});
});

For some odd reason, it wouldn't work, and I've checked the php code, and it works fine. Any suggestions?

like image 858
Majo0od Avatar asked Apr 22 '12 22:04

Majo0od


3 Answers

Try this:

$(window).unload(function(){
    $.ajax({
        type: 'POST',
        url: 'script.php',
        async:false,
        data: {key_leave:"289583002"}
    });
});

Note the async:false, that way the browser waits for the request to finish.

Using $.post is asynchronous, so the request may not be quick enough before the browser stops executing the script.

like image 85
stewe Avatar answered Sep 28 '22 07:09

stewe


This isn't the correct way of doing this... Suppose the OS just hangs or something happens in the browsers process then this event wont be fired. And you will never ever know when the user has left, showing him/her online ever after he/she has disconnected. Instead of this, what you can do is.

  1. Try connecting a socket so that you can know the user is disconnected when the socket is disconnected
  2. You can send a request to the server (say after every 1 sec) so that you can know that the user is still connected. If you didn't receive the request - even after 2 secconds - disconnect the user.
like image 35
Parv Sharma Avatar answered Sep 28 '22 05:09

Parv Sharma


Try to add popup (prompt("leaving so early?")) after $.post. It may work. Tho it may be bad user experience. :)

like image 30
Milan Jaric Avatar answered Sep 28 '22 07:09

Milan Jaric