views:

489

answers:

2

I want to call an URL in the unload-Function of a Webpage but in the unload-function the get request is not working. My code looks like this:

$(window).unload( function () { 
   jQuery.get("someurl")
} );

We want to be informed about the closing of the window for some logging of user actions. Is it possible somehow?

If i add an alert() after the jQuery.get(), the Get-Request has enough Time, to do this, but that's not what we prefer.

+8  A: 

Use:-

jQuery.ajax({url:"someurl", async:false})
AnthonyWJones
+1  A: 

You need to use the onbeforeunload event directly. In that event, you can fire off an ajax call. This is one place where jQuery isn't really helpful (yet). A couple notes:

Don't return anything from the onbeforeunload event or the browser will display a "are you sure you want to leave this page" popup to the user

If you make the ajax call sync, it will stall the page unloading while it is running. If you make it async, the page will change while the call is running (you just can't have javascript event handlers for that call). Since jQuery wires up event handlers, its ajax support isn't as useful here.

window.onbeforeunload = function() {
   var URL = 'someplace';
   var request = null;

    if (window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (request) {
        request.open("GET", URL, false);
        request.send();
    }
}
Erv Walter
the onBeforeUnload event is not standard and so therefore should not be used... Opera, for example, does not support it.
J-P