Majo0od Majo0od - 5 months ago 7
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:

$(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?

Answer

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.

Comments