I have tried for “unload” and “beforeunload” binding in following code, but none of the browser is sending a request:
$(window).bind('unload', function(){
$.ajax({cache: false,
dataType: "script",
url: "test.php"
});
});
Any suggestion?
The browser doesn’t wait for this code to finish…it’s running just fine 🙂 Add an
alert('hi')to see it running.The problem you’re seeing is typical of
unloadissues, the browser navigates away well before a request gets fired off in your case…and it should really, no code you’re running should have to complete before I’m allowed to move onto the next page. This is just howunloadbehaves. You could make the call synchronous to hold the user there, but please don’t do this.The
unloadevent was created on window mainly to clean up anything left around in the DOM you needed to, more-so when garbage collection wasn’t as good as it is now (and still isn’t in IE)…it wasn’t really designed with AJAX or metric tracking in mind.