Showing posts with label editable. Show all posts
Showing posts with label editable. Show all posts

Thursday 1 August 2013

HTML5 contenteditable save, re-save and save again

The HTML5 contenteditable attribute is really useful, but when you've got my typing skills, you'd really like to keep saving as you go. In the example below I'm writing to a text file for simplicity. I've got a few things going on.

  • If the text file exists or has data in there, I use it. Otherwise, the editable paragraph holds a default string.
  • I use a form submit to kick off a jQuery event.
  • The jQuery function calls a PHP script to write the contents of my editable paragraph to the file.

This way I can keep pressing the submit button as I go, which will just update the text file with the current editable paragraph contents.

Here's the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Editable jQuery save</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<p id="content" contenteditable="true">
<?php
$text = file_get_contents('test.txt');
if(!empty($text))
{
echo $text;
}
else
{
echo 'Put some text here.';
}
?>
</p>
<form>
<input type="submit" />
</form>
<script>
(function()
{
$('form').submit(function()
    {
        $.post('set.php',
        {
            content:$('#content').text()
        }, function(data)
        {
        if(data)
        {
        console.log(data)
        }    
        });
        return false;
    });
})();
</script>
</body>
</html>

And set.php

<?php
if(isset($_POST['content']))
{
file_put_contents('test.txt', $_POST['content']);
}
else
{
echo 'write was not successful';
}
?>