Skip to content Skip to sidebar Skip to footer

Send An Ajax Call On Beforeunload/unload

Scenario: I am creating an event registration module in which a user would choose a date from a calendar for booking, fill some input fields and pay up to book the date. One of th

Solution 1:

I needed something like that. But unfortunately calling the backend in onBeforenUnload is not reliable. Most AJAX calls will not reach the backend (some may); The only guaranteed call is with navigator.sendBeacon(url, data). It sends POST request even the browser is closed.


Solution 2:

You can post data with async: false like this:

$(window).unload(function () {
            $.ajax({
                type: 'POST',
                async: false,
                url: 'your url',
                data: {  }
            });
        });

Solution 3:

Try console.log and return in your onbeforeunload method. maybe user leaves the page before your ajax goes through.

See: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Since 25 May 2011, the HTML5 specification states that calls to

  • window.alert()
  • window.confirm()
  • window.prompt()

commands may be ignored during this event.


Solution 4:

You can make the client send out a "heartbeat" every 30 seconds or so to the server, and update a record in the database with a timestamp of the last sent heartbeat along with a reference to the booking date. Then run a cronjob which runs every minute or so, which checks all of those records, and if one of them is over let's say over 120 seconds old, then delete the record.


Post a Comment for "Send An Ajax Call On Beforeunload/unload"