I have a js change event which saves data via an Ajax request when a user leaves a control. This works fine unless the user decides to leave the page. The Ajax then does not complete and the data is not saved. Looking at Ajax request with JQuery on page unload I see that if I make the request synchronous the Ajax request will complete. I have tried this and it does work. However, I am calling this change event whenever the user moves from control to control on the page and I do not want all these calls to be synchronous.
I tried using Alert for unsaved changes in form to check for unsaved data. This triggers the beforeunload
function fine when there is a control with unsaved data, however I can't work out what to put in the beforeunload
function.
- I can put in an alert. When the user cancels the alert my change code runs and all is fine. However, it is annoying and confusing for the user to have a dialog box pop up when normally data is saved without them having to do anything
- I tried Using jQuery to test if an input has focus to find the element which has focus and then force my change function to run on this. However, I couldn't find an element with focus (may have been doing something wrong here?)
- I tried using a sleep function to give the Ajax call time to run but that didn't work either
- I tried setting the focus into another control - no luck
Any ideas about what else I might try or what I might be doing wrong with any of the things I've tried? Can I somehow have an invisible alert that is triggered and cancelled without the user having to do anything?