Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax request with JQuery on page unload

Tags:

jquery

ajax

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?

like image 821
Rob Avatar asked Nov 30 '09 18:11

Rob


2 Answers

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.

like image 199
Nate B Avatar answered Oct 21 '22 05:10

Nate B


Try calling it with async = false;

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

I just tried it.

like image 22
Orson Avatar answered Oct 21 '22 06:10

Orson