How do I make an ajax call on page unload?

I have a panel where users can switch to some input values ​​to customize the look of the page.

I want to save these changes to the DB table, so when the user comes back, the toolbar appears according to the specific user config retrieved from the DB.

I know how to send these values ​​to the DB and how to get them

I don't want to make ajax calls every time the user changes the configuration.

Instead, I think this senario would be better:

  • Upload to the page (if necessary, get the database configuration)
  • The user toggles ui config items (like checkboxes, select, etc.) and the corresponding client-side changes happen (some divs are hidden, some others are shown, etc., and the config input is stored in a hidden field), but no ajax call is made .
  • When the user clicks on a link to another page, the configuration input values ​​(which were stored in a hidden field) are sent to the DB via an ajax call.

MY QUESTION

One solution (?) Would be to use the event onbeforeunload

like this:

window.onbeforeunload = function(e) {
   // Perform the ajax call
   return 'Do you want to save the configuration changes?';
};  

      

But if the user's browser prevents pop-ups, the function will fail?

Is there a way to make an ajax call on an event onbeforeunload

without invoking the dialog?

+3


source to share


2 answers


Not. During unloading, the browser will kill all pending requests. Thus, AJAX may or may not come to the server. You also cannot do this inside an event handler beforeunload

, because the first A in AJAX means: Asynchronous -> Just push the request onto the stack and eventually execute it. Thus, the request will only be considered after the handler returns. But very soon after that, the browser will kill everything related to this page.

The solution is to always push updates to the server while users make changes. Place them in a special "temporary" table from which you can restore the state later.



You can also use something like localStorage

in a browser, but then the data won't move with the user. For example, if they were working on a tablet and that broke or lost power, they could go to their computer to continue where they left off.

+6


source


You cannot guarantee that the Ajax call will complete this way, see Aaron's answer. My suggestion would be to use something like localStorage

read / write user settings.



If you need the user's appearance to persist across multiple devices, add a periodic request to read / write the latest updates from localStorage to the central DB.

0


source







All Articles