0

I've ran into a bit of a problem trying to run synchronous AJAX call using the event $(window).unload.

According to the documentation though:

As of jQuery 1.8, the use of async: false is deprecated.

I'm trying to send the user's data (a name, an age and a large string of numbers) to a php file all in one go just before they exit the page.

Is this possible?

Thanks.

4 Answers4

1

You can try beforeunload,

$(window).bind('beforeunload', function() {
//Do your processing
return "You want to close the window?"
});
Matt
  • 1,953
  • 1
  • 19
  • 42
  • My problem here is the ajax request, rather than the event triggering. –  Jul 18 '12 at 07:56
1

I would not even try to do this if this data is important because there is no guarantee that even the unload event occurs. The person could shutdown the browser, pull the plu on the computer etc.

I would have a save button on the page instead.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • The data isn't very important, I would be happy if it only worked 90% of the time. –  Jul 18 '12 at 07:57
0

Yes, but you don't know if the browser will interupt the request before it leaves your computer. I think it depends on the browser. Almost for sure, there is no way for the client to handle the response.

Simon Edström
  • 6,461
  • 7
  • 32
  • 52
0

Look at these:

Can the unload Event be Used to Reliably fire ajax Request?

Why can't I use jQuery to fire an AJAX request from an unload event handler?

Running a PHP through Ajax on Unload

Conclusion:

It's better not to have async request. And you must set ignore_user_abort() in your php so it doesn't terminate when connection drops!

Community
  • 1
  • 1
Ali
  • 21,572
  • 15
  • 83
  • 95