Ajax request with jQuery on unload page

I am 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, a success warning is never displayed, and this request does not seem to even hit the server. What am I doing wrong?

+59
jquery ajax
Nov 30 '09 at 18:44
source share
6 answers

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

+67
Nov 30 '09 at 18:48
source share

Try calling it with async = false;

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

I just tried it.

+17
Nov 30 '09 at 18:59
source share

The best solution is to use navigator.sendBeacon . This is a completely new functionality that is starting to be implemented in new versions of browsers. The feature 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 is sent in browsers that do not yet support the new functionality, 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 an onsuccess callback.

+7
May 19 '15 at 12:58
source share

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

+3
Apr 21 '15 at 18:10
source share

Your function and Ajax call look great, so I assume that your browser window is closed before the ajax call has time to go to the server and back. The ajax call may return something when the window closes, try adding an error function to your ajax call to see if this is the case:

 error: function (xhr, textStatus) { alert('Server error: '+ textStatus); } 
0
Nov 30 '09 at 18:46
source share

Maybe you will have more success with the onbeforeunload event?

  $(window).bind('beforeunload', ... 
0
Nov 30 '09 at 18:58
source share



All Articles