Search

Data Saving in Case of Browser Crashes

0 views

So a few days ago I posted a //used to save your form info (title/body) in case your browser crashes function saveText() {     var titleField = $("title");     var bodyField = $("body");     var expire = new Date();     expire.setDate(expire.getDate()+7);     //write title to cookie     var cookieString = 'savedtitle=' + escape(titleField.value)+'; expires=' + expire.toGMTString() + '; path=/';     document.cookie = cookieString;     cookieString = 'savedbody=' + escape(bodyField.value) + '; expires=' + expire.toGMTString() + '; path=/';     document.cookie = cookieString;     window.setTimeout('saveText()',5000); } window.setTimeout('saveText()',5000); The first thing I want to point out are these two lines: var titleField = $("title"); var bodyField = $("body"); These are Spry (copied from Prototype) shorthands for: var titleField = document.getElementById("title"); var bodyField = document.getElementById("body"); Outside of that - everything else is vanilla JavaScript. JavaScript lets you add cookies by simply setting the document.cookie value. Also note that document.cookie isn't a simple string. If you run document.cookie = something multiple times, you end up with multiple cookies. The format for a cookie string is name=value; expires=DATE; path=PATH. In my case I simply used a cookie that expires in 7 days and a path of /. Lastly I have a window.setTimeout, both outside of the function and inside, that will run this code every 5 seconds. Any duration is fine really. To restore the values, I used this set of code on the server side: <cfif not structKeyExists(form, "title") and structKeyExists(cookie, "savedtitle")>     <cfset form.title = cookie.savedtitle> </cfif> <cfif not structKeyExists(form, "body") and structKeyExists(cookie, "savedbody")>     <cfset form.body = cookie.savedbody> </cfif> Basically I simply ensure that I'm not already posting and see if I have anything in the cookie. I clear out the cookies using this code: <cfcookie name="savedtitle" value="" expires="now"> <cfcookie name="savedbody" value="" expires="now"> As you can see, this is a pretty trivial implementation. Anyone else using something like this in their applications? http://ray.camdenfamily.com

Raymond Camden is Vice President of Technology for roundpeg, Inc. A long time ColdFusion user, Raymond has worked on numerous ColdFusion books and is the creator of many of the most popular ColdFusion community web sites. He is an Adobe Community Expert, user group manager, and the proud father of three little bundles of joy.

Suggest a Correction

Found an error or have a suggestion? Let us know and we'll review it.

Share this article

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!