Babar Babar - 29 days ago 5x
Javascript Question

Making ajax call on navigating away from page

I am working on a site that has multiple links to other sites. What I want is to send an ajax call to report that the user is going away when someone clicks and navigates away from the page. I put an alert on click of the links, which works but for some reason the controller never gets the ping.

Any assistance will be appreciated on how to achieve it.


You can try to simply set click event handler which will check the href attribute of every link before navigating. If it goes to another website, the handler sends AJAX request and then (after server responding) redirects to the page.

var redirect = '';
$('a').click(function() {
    if ( != {
        if (redirect) return false; // means redirect is about to start, clicking other links has no effect
        redirect = this.href;
            url: '/away', 
            success: function(){document.location.href = redirect;}
    return false;

However it can't work properly, if user has opened your page in multiple tabs.