Skip to content Skip to sidebar Skip to footer

How To Perform An Ajax Call On Page Unload?

I have a dashboard where users can toggle some input values in order to configure the appearance of the page. I want to store those changes in a DB table, so when user comes back,

Solution 1:

No. During unload, the browser will kill all pending requests. So the AJAX might or might not arrive at the server. You also can't do it inside the handler of the beforeunload event because the first A in AJAX means: Asynchronous -> Just put the request on the stack and eventually execute it. So the request will be looked at only after the handler returns. But very soon after that, the browser will kill anything related to the page.

The solution is to always send updates to the server while the users makes changes. Put those into a special "temporary" table from which you can restore the state later.

You could also use something like localStorage in the browser but then, the data wouldn't move with the user. For example if they were working on an tablet and that broke or had a power loss, they could move to their PC to continue where they left off.

Solution 2:

You can't guarantee that an Ajax call will complete in this way, see Aaron's response. My suggestion would be to use something like localStorage to read / write the user's settings instead.

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

Post a Comment for "How To Perform An Ajax Call On Page Unload?"