Majo0od Majo0od - 1 year ago 82
Ajax Question

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:


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

Answer Source

Try this:

        type: 'POST',
        url: 'script.php',
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download