Welcome to WebmasterWorld Guest from 54.224.83.221

Forum Moderators: phranque

Autosaving a textarea

     
7:18 am on Jul 3, 2018 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month

joined:Mar 15, 2013
posts: 827
votes: 71


I'm hoping to get some feedback from you guys on the best way to do this.

First, I test to see if the browser supports contenteditable, then set a cookie showing the support; if the cookie exists then the user has a contenteditable area, and if not they get a textarea.

What I'm trying to accomplish is saving what they've typed before they submit it, so that if they leave the page or something happens then they don't lose everything.

My first thought process is to first check to see if they've typed anything every 5 seconds using Javascript's setInterval; if they have then I test to see if the contents are different from what's already saved (overkill?), and if it's different then I set the cookie.

Here's the code I'm using:

// in PHP I split the URL in to an array
$urlArr = explode('/', $_SERVER['REQUEST_URI']);

// create a name for the cookie
// becomes something like 'classifieds' or 'classifieds-12345';
$saveName = $urlArr[1];
if ($_GET['id'] && is_numeric($_GET['id']))
$saveName .= '-' . $_GET['id'];

// show saved data if it exists
if ($_COOKIE[$saveName])
$comment = $_COOKIE[$saveName];

// then in Javascript
setInterval(
function() {
// I use .html() for contenteditable, .val() for textarea
var commentVal;
if ($('#comment').html()) commentVal = $('#comment').html();
if ($('#comment').val()) commentVal = $('#comment').val();

if (commentVal && commentVal != getCookie('$saveName'))
setCookie('$saveName', commentVal);
}
, 5000);

// then in HTML; I'll spare you the contenteditable code
<textarea id="comment">$comment</textarea>


The functions setCookie and getCookie are separate functions that I've been using for years.

So I guess I'm asking 3 questions here:

1. Do you think that using setInterval to save it every 5 seconds is the right move? I also considered running it onKeyUp, but THAT seemed like way too much processing.

2. Do you think that it's overkill to use getCookie, instead of just overwriting if it's the same?

3. Thoughts on the idea and code in general... is there a better way to accomplish the same thing?

I realize that there's a general limitation of about 4,000 characters in a cookie, so the occasional post might not get saved (ironically, the ones that are the longest and take the most work are the ones least likely to be protected). And using Rich HTML on a contenteditable means that 4,000 characters isn't very unrealistic at all, especially if they copy and paste something from another site. Maybe a better option would be to use Ajax and save it to MySQL instead of a cookie?