Ajax request with JQuery on page unload

I'm trying to do this:

$(window).unload( function () { 

$.ajax({
    type: "POST",
    url: "http://localhost:8888/test.php?",
    data: "test",
    success: function(msg){
         alert( "Data Saved: " + msg );
    }
}); 
alert (c);
});

However, the success alert is never shown, nor does this request seem to be even hitting the server. What am I doing wrong?


I believe you need to make the request synchronous instead (it's asynchronous by default) using the async : false parameter.

Synchronous requests lock up the browser until they complete. If the request is asynchronous, the page just keeps on unloading. It's quick enough that the request never even has time to fire off.


Try calling it with async = false;

jQuery.ajax({url:"http://localhost:8888/test.php?", async:false})

I just tried it.


The best solution is to use navigator.sendBeacon. It is brand new functionality which is starting to get implemented in new releases of browsers. The function is available in browsers newer than Chrome 39 and Firefox 31. It is not supported by Internet Explorer and Safari at the time of writing. To make sure your request gets send in the browsers that don't support the new functionality yet, you can use this solution:

var navigator.sendBeacon = navigator.sendBeacon || function (url, data) {
  var client = new XMLHttpRequest();
  client.open("POST", url, false); // third parameter indicates sync xhr
  client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  client.send(data);
};

This function does not allow you to register a onsuccess callback though.


The HTML 5 Specification states that alert(), prompt(), etc. will not be available during the window.unload() event. Please see window.unload() for more details. You can check the result by using console.log('success'); instead of alert().