views:

143

answers:

2

Hi guys,

I am trying to execute a webservice method call from the javascript on the page, just before the user leaves the page. I got the javascript speaking the webservice perfectly. However, when I try to hook the javascript function to the window.onbeforeunload event, nothing happens.

<script type="text/javascript" language="javascript">
            window.onbeforeunload = LogEnd;

            function LogEnd() {                    
                OnlineAgent.AnalyticsService.FeatureUseEndLog(63, OnCallComplete, OnCallFailed);
            }

            function OnCallComplete(result) {
                //var elem = $get("Results");
                //elem.innerHTML = result;
            }

            function OnCallFailed(result) {
                //var elem = $get("Results");
                //elem.innerHTML = "Failed: " + result;
            }
        </script>

The method on the webservice returns no values. I am unsure what to do with the onsuccess and onfailed callback functions, so I placed empty functions.

Any ideas guys? Has anyone tried to do this before?

+1  A: 

basically you've got a race condition problem. If the request completes before the page changes then it'll work. Most of the time, though, it will fail.

Jonathan Fingland
I thought as much! I want to record the datetime the user leaves the page, and store it into a database. How do analytics products (e.g. google analytics) figure out how long on a user stayed on a page?
pwee167
Unless they poll the webservice at very small intervals, but that would be costly...
pwee167
Honestly, I don't know. A page I know that is using google analytics requested a javascript file and a 1x1 transparent gif. After that, firebug showed no activity with google-analytics.
Jonathan Fingland
+1  A: 

You can use SYNCHRONOUS request (SJAX) and it seems to work in all browsers.

If you look at the basic XmlHttpRequest javascript objects there is a parameter to use Asynchronous...just pass false.

Jeremy