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.
; 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;
if ($_GET['id'] && is_numeric($_GET['id']))
$saveName .= '-' . $_GET['id'];
// show saved data if it exists
$comment = $_COOKIE[$saveName];
// I use .html() for contenteditable, .val() for textarea
if ($('#comment').html()) commentVal = $('#comment').html();
if ($('#comment').val()) commentVal = $('#comment').val();
if (commentVal && commentVal != getCookie('$saveName'))
// then in HTML; I'll spare you the contenteditable code
The functions setCookie
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?