views:

929

answers:

5

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? Thanks!

A: 

Your function and Ajax call look fine, so my guess is that your browser window is closed before ajax call has time to go to the server and back. The ajax call might return something when the window is closing, try adding error function to your ajax call to see if that's the case:

error: function (xhr, textStatus) {
    alert('Server error: '+ textStatus);
}
Marek Karbarz
I don't really need it to come "back" (i.e. that alert of success is not necessary, just used for debugging purposes). However, I do need the ajax request to be fired before the unload finishes.
Rob
+4  A: 

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

Nate B
A: 

Maybe you'd have more success using the onbeforeunload event instead?

   $(window).bind('beforeunload', ...
Scott Evernden
A: 

Try calling it with async = false;

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

I just tried it.

Colour Blend
A: 

I have tried both "unload" and "beforeunload" binding but except FF now of the browser is sending the request to server:

$(window).bind('unload', function(){
       $.ajax({cache: false,
        dataType: "script",
            url: "test.php"
        });
    });

Any suggestion?