Skip to content Skip to sidebar Skip to footer

How Do I Send An Ajax Request Upon Page Unload / Leaving?

window.onbeforeunload = function() { return $j.ajax({ url: '/view/action?&recent_tracking_id=' + $recent_tracking_id + '&time_on_page=' + getSeconds() }); }

Solution 1:

You don't need to return anything, just fire the ajax call.

window.onbeforeunload = function(e) {
    e.preventDefault();
    $j.ajax({ url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + &time_on_page=" + getSeconds()
    });
}

If you are using jQuery, you can try binding to the .unload() event instead.

Solution 2:

onbeforeunload allows you to return a string, which is shown in the 'Do you want to leave' confirmation. If you return nothing, the page is exited as normal. In your case, you return the jqXHR object that is returned by the JQuery ajax method.

You should just execute the Ajax call and return nothing.

Solution 3:

Why are you returning the reference of function to global pool? It should be like this:

window.onbeforeunload = function() {
 $j.ajax({
    url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
 });
}

Solution 4:

To the best of my understanding, the onbeforeunload function will only return an alert. This was done to prevent the annoying popups of a few years back.

I was building a chat client a while back and the only way i could figure out to do something like this is to do a setInterval function that updated a timestamp, then checked for timed out users and removed them. That way users that didnt "check in" within a certain interval would be removed from the room by other users still logged in.

Not pretty, or ideal, but did the trick.

Post a Comment for "How Do I Send An Ajax Request Upon Page Unload / Leaving?"