Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
Chuck D Avatar asked Feb 07 '11 16:02

Chuck D


2 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;
});
like image 170
jAndy Avatar answered Nov 11 '22 09:11

jAndy


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!

like image 23
Leland Richardson Avatar answered Nov 11 '22 09:11

Leland Richardson