Skip to content Skip to sidebar Skip to footer

Jquery Unload With An Ajax Call Not Working In Chrome

This is my very simple code snippet: $(window).unload(function() { $.ajax({ url: 'stats_pages.php?last_id='+$('#last_id').val(), }); }); Simple enough.

Solution 1:

Set ASYNC : false in your ajax call

$(window).unload(function() {
        $.ajax({
            url: 'stats_pages.php?last_id='+$("#last_id").val(),
            async : false,
        });
});

Solution 2:

As of today, this will still fail with newer versions of Chrome. The problem is with the unload event and Chrome. It seems to have been a problem since Chrome 14. You can read more about the issue from a jQuery bug ticket: http://bugs.jquery.com/ticket/10509.

There is also a fix for Chrome listed on that link above:

window.onbeforeunload = function() { 
  $.ajax({
       url: 'stats_pages.php?last_id='+$("#last_id").val(),
       async : false,
  });
}

Solution 3:

Neither of the solutions above were acceptable to me. The first because async AJAX calls can cause the client to behave badly if the server is slow, and the second because we already use the onbeforeunload event to generate an "Are you sure?" message for users leaving a page where they have made changes. I experimented with setTimeout and jQuery's delay(), but I came to the conclusion that as soon as the thread goes into sleep mode, Chrome kills the thread, and apparently the AJAX call needs a little bit of time to formulate the request for it to be successful. So eventually I was able to resolve this problem with a very low-tech loop which never put the thread into a sleep state, and kept the thread running for another 50 milliseconds.

var start = newDate().getTime();
for (var i = 0; i < 1e7; i++) {
    if ((newDate().getTime() - start) > 50) {
        return;
    }
}

With this change, the AJAX call now fires correctly in Chrome with no noticable lag on the client side.

Post a Comment for "Jquery Unload With An Ajax Call Not Working In Chrome"