-2

I want to get an Update about this topic.

I find many posts here on how to use unload() and onbeforeunload events, but there are not working for me. I try putting inside and outside $(document).ready(function(){} but it is not resulting. I will show the post (5 years ago) where it lead me to create a new one. How should we use? Thank you!

jquery beforeunload when closing (not leaving) the page?

I try using without on, with onbeforeunload etc.

Does not run the code inside the event. :S

This is the code:

$(window).on("beforeunload", function () {
    return 'hi';
    $.ajax({
        type: 'POST',
        url: 'Cierre_unload.php',
        success: function () {

        }
    })
})
  • 1
    Share your code to determine which part is not working – swapnesh Apr 19 '19 at 16:47
  • add an event listener to the window object. window.addEventListener("unload", function() { //do stuff }) – GifCo Apr 19 '19 at 16:51
  • 2
    The page is unloading. Any async requests will be dropped. You *might* be able to use a synchronous request but even that may be washed away by the browser. – Niet the Dark Absol Apr 19 '19 at 16:53
  • - GiffCo , its not working :S (I use Chrome) Can't figure it out... – Xabier Aparicio Muñoa Apr 19 '19 at 16:54
  • You can't do this. The older question you linked to is outdated. `onbeforeunload` and window unload handlers can really only be used to show a confirm dialog at this point. – Daniel Beck Apr 19 '19 at 16:55
  • Only works for an alert message, then? – Xabier Aparicio Muñoa Apr 19 '19 at 16:58
  • Thank you Niet the Dark Absol for clarifying :) – Xabier Aparicio Muñoa Apr 19 '19 at 17:00
  • BANG! WORK IT! I CLOSE THE WINDOW AND DID THE AJAX REQUEST! I CHECK IT IN MYSQL UPDATE! :) The event triggers whenever the user leaves the page :) – Xabier Aparicio Muñoa Apr 19 '19 at 17:12
  • Please don't edit your question to include the answer (or the word "SOLVED" in the title). You can post an answer on your own question, if you've found a solution. (Are you sure you have? Browsers explicitly prevent async requests in unload handlers: https://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-in-chrome) – Daniel Beck Apr 19 '19 at 17:30
  • Hi Daniel Beck! It worked the AJAX request, I check it in MySQL. Probably worked with beforeunload event but haven't try it with unload. Okay! I new in here when it comes to posting. Thanks for the next time! :) Gonna check the post now... – Xabier Aparicio Muñoa Apr 19 '19 at 17:35

1 Answers1

0

UPDATE

I probably made a mistake but I sort it out! :) The AJAX request is working whenever the user leaves the page :)

IMPORTANT

To accomplish this task it should be use beforeunload event, which run just before leaving the page (unloading the page). For example, I close the window and the AJAX request was made, recorded the progress with MySQL.

Hope you find it useful :)

Open to a debate, whether it's a good practice to use :)