Reputation: 65143
window.onbeforeunload = function() {
return $j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
this what I have, but it returns an alert with [object Object]
how do I just execute the AJAX?
note: when I just don't return anything, the server doesn't show that it is receiving the ajax request.
Upvotes: 0
Views: 2907
Reputation: 1074495
Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page).
In the rare case when you need to send information as the user is navigating away from the page (as Aaron says, avoid this where possibl), you can do it with sendBeacon
. sendBeacon
lets you send data to your server without holding up the page you're doing it in:
window.addEventListener("unload", function() {
navigator.sendBeacon("/log", yourDataHere);
});
The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).
Note that the unload
event may not be reliable, particularly on mobile devices. You might combine the above with sending a beacon on visibilitychange
as well.
Upvotes: 0
Reputation: 1485
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.
Upvotes: 0
Reputation: 3765
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()
});
}
Upvotes: 0
Reputation: 116110
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.
Upvotes: 1
Reputation: 28699
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.
Upvotes: 1