Saturday, March 24, 2012

AJAX and using the onbeforeunload event

When my form loads I set a variable in the database to lock the form. Only one user at a time can edit/view the form. When they click the Save button I remove the flag via a database query and the form is no longer locked. This works great when the user clicks the Save button. But what do you think happens when they do not click the Save button and they leave the page? Since no button on the form was pushed I cannot update the database to unlock the form. So I thought of using the onbeforeunload event. I am using it now to tell the user that if they leave the form before they click the Save button their data will be lost. What I would like to be able to do is when the user does click the OK button on the alert box and they do leave the form I would like to run a sql statement to update the database and to unlock the form. Is this do-able? With or without AJAX?

Just theorizing... but since you succesfully have the alert box going - on the unload event.. can you tie up an asynchpostback event in javascript to handle this - once the request is fired all should be good (the migration guide has some examples of this I believe...) or as an alternative you can popup a modal (however at that point the user can just hit the back button again anyways)...

For a double measure - either use an event timer in the global.asax that call the stored procedure. One additional field in the database would be needed "TimeofRecordLock"... and modify the sp to search for all records that time expired from initial lock that excedes your lock time... get reset... Any postbacks that occur just have the sp that does whatever or the code behind itself to update the new time value... - then you could have a special updatepanel that is set to refresh on a timer - "Record is locked" kinda of deal - when timer expires and no updates have been made - it provides another option - "re-lock record"... if it trys to and another user grabbed it then it reverts to a option - notify me when record is unlocked... The cool thing about ajax you can make that happen and the user really needs to not do anything...

You could also create a cache that that stores the time and you update the time in cache and map it to the session of the user ...and on clearing the cache entry you run through all sessions tied to records and perform a batch sql to reset those values in the db...

Just some thoughts as you have multiple scenarios - not only in the ajax enviroment - to consider...


Thanks for all the suggestions Jody. I am most interested in the asynchpostback on the unload event. Seems that this would be the best way to go. Where is the migration guide?

No comments:

Post a Comment