Skip to content

Instantly share code, notes, and snippets.

@smottt
Created April 11, 2012 15:31
Show Gist options
  • Save smottt/2360062 to your computer and use it in GitHub Desktop.
Save smottt/2360062 to your computer and use it in GitHub Desktop.
contenteditable example
<html>
<head>
<title>contenteditable example</title>
</head>
<body>
<!-- html code ... -->
<article contenteditable="true" date-edit-url="update.php">
Some content here ...
</article>
<!-- some more html code ... -->
</body>
</html>
$(function() {
var content_holder, content;
var selector = 'article[contenteditable="true"]';
// prevent clicks inside editable area to fire
// a click event on the body
// and therefor saving our content before we even edit it
$(selector).click(function(e) {
e.stopPropagation();
});
// initialize the "save" function
$(selector).focus(function(e) {
content_holder = $(this);
content = content_holder.html();
// one click outside the editable area saves the content
$('body').one('click', function(e) {
// but not if the content didn't change
if ($(e.target).is(selector) || content == content_holder.html()) {
return;
}
$.ajax({
url: content_holder.data('edit-url'),
type: 'POST',
dataType: 'json',
data: { body: content_holder.html() },
success: function(json) {
content_holder.effect('highlight', {'color': '#0f0'}, 3000);
},
error: function() {
content_holder.effect('highlight', {'color': '#f00'}, 3000);
content_holder.html(content);
}
});
});
});
});
<?php
// note the php 5.4 short array syntax :)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// clean any existing new line characters
$body = str_replace(["\n", "\r"], '', $_POST['body']);
// we get back actual HTML instead of new line characters
// so we need to replace them with new lines for proper display
// later on
$body = trim(preg_replace('~(<br\s*/?>)~im', PHP_EOL, $body));
// content is ready to be updated in the database
// ...
return print json_encode(['success' => 1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment