AJAX calls immediately before leaving page

I want to perform a simple AJAX get request when a user clicks a link to another page. Will the AJAX call complete or will it stop because the user is leaving the page that initiated the AJAX request? I don't really care about the response from the get request.

Any Thoughts or Ideas?

Answers


If you just want to send data to your server and don't care about the resonse, you might want to try a beacon request. That basically is, a fire and forget thing which works like this:

function sendInfo(something) {
     var beacon = new Image();
         beacon.src = '/somepath/script.pl?info=' + something;
}

$('a[href^=http]').bind('click', function(e) {
    sendInfo(escape(e.href));
});

Well, this technique does not block so it might be a race condition whether or not the browser will fire the request (I didn't test it on this purpose). To be sure that the request will fire, invoke an ajax call like this:

$('a[href^=http]').bind('click', function(e) {
    $.get('/somepath/script.pl', {info: escape(e.href)}, function(data) {
        location.href = e.href;
    });

    return false;
});

I know that this question was asked, answered, and accepted a long time ago... but I just recently asked myself the same question, found jAndy's answer, and slightly improved upon it (regarding the Chrome compatibility issue) and thought I would post my findings.

Andy's beacon answer was nice and simple, but as SirDarius has mentioned, Chrome seems to be optimized to ignore it.

I modified jAndy's code to be as follows:

function sendInfo(something) {
     var beacon = new Image();
         beacon.src = '/somepath/script.pl?info=' + something;
}

$('a[href^=http]').bind('click', function(e) {
    sendInfo(escape(e.href));
    setTimeout(function() {window.location.href=e.href;},0); // change window location on timeout
    return false; // cancel current window location change
});

and this seemed to get rid of the issue.

Thanks Andy!


Need Your Help

Old Fashioned Java countdown alarm

java swing vlcj

new years eve is coming and im thinking what are the possible ways to program a old fashioned countdown timer into java to use it as a countdown of 10 seconds.

how to connect to php parser in netbeans platform

java php netbeans netbeans-plugins netbeans-platform

I am writing a code completion plugin for a PHP library in Java / Netbeans Platform.