views:

270

answers:

3

I was just reading http://stackoverflow.com/questions/1619930/how-to-check-users-leave-a-page earlier on when suddenly I thought of performing AJAX when user leaves the page to send analytical data back to the server.

Is performing AJAX on the onunload event a good or bad practice/implementation?

A: 

I think you'll end up in race condition

If you spawn another thread, the one who did the AJAX call will be destroyed and the page will unload (because the page was waiting for this thread to finish)

Anyways, unload event are to be avoided at all costs in my opinion! Unless things have changed in the last couple years.. where I told to myself to never do it again :P

Good luck

Mike Gleason jr Couturier
+1  A: 

To get any reliable form of data you will need to pause the action until the ajax post goes through - the page will usually be terminated before that can happen.

In all reality, there is no way to detect every way a user can get out of a page, onunload, if its not fast enough, will be interrupted.

Justin
+1  A: 

Performing AJAX calls on unload does not work very well in all situations. Usually, the web browser closes the panel almost immediately and the AJAX call may be lost.

If you want to send analytical data, I suggest to send them in advance of closing the page. For example, send it after 5sec, then 10sec, 20sec, etc. Use unique identifier to find the latest information. The interval is up to you based on how precise measuring you need and not to annoy the user for additional bandwidth :-)

Viliam