HTML5 In-line text editing and storing to database

September 28, 2011 HTML5, jQuery, PHP 23 comments

The HTML5 specification includes contentEditable attribute, which has been supported by most of browsers for quite some time. It gives ability to edit the page directly in the browser window. You can specify particular parts of a page which should be editable in a very easy way. At its simplest, all you have to do is to add the tag attribute contentEditable to the element. The contenteditable attribute can be applied to any HTML element, for example images, lists, and even video content. However, it allows to edit the text only, the other elements can be only removed.


Another limitation of contentEditable is that, it does not provides means for users to save the edited content of the page. So, in order to save the edited content, we will use jQuery with PHP to store the content in mySQL database.

The contentEditable attribute is supported by all major web browsers including Internet Explorer 6+, Firefox 4+, Safari 3.2+, Chrome 11+, and Opera 10.6+.

Following is screenshot of the tutorial output, you can see live demo and download the files at the end of article.

So, lets start with HTML code:

<div id="status"></div>
	<div id="content">
		<div id="editable" contentEditable="true">
			Lorem ipsum dolor sit amet...
		</div>
		<button id="save">Save</button>
	</div>

We created a div #editable, which contains the editable text, with a button to save the changes. We will use div #status to display the server message.

You can add CSS as you wish, but important thing to remember is that, initially we will like to hide the Save button. We would like to show the button, only if the #editable div is clicked. Similarly, as the #status will be empty initially, so we will hide it as well.

#status{
	display:none;
	margin-bottom:15px;
	padding:5px 10px;
	border-radius:5px;
}

#save{
	display: none;
	margin: 5px 10px 10px;
}

You can add CSS for other elements as you like.
Now, lets start the jQuery code.

$("#editable").click(function (e) {
	$("#save").show();
	e.stopPropagation();
});

$(document).click(function() {
	$("#save").hide();
});

The above code shows the save button if anywhere in the editable div is clicked, and hide the button if anywhere outside the div is clicked.
Now, we should post the text data to the server so that we can save it in the database.

$("#save").click(function (e) {
	var content = $('#editable').html();
		$.ajax({
			url: 'save.php',
			type: 'POST',
			data: {
            content: content
			},
			success:function (data) {
				if (data == '1')
				{
					$("#status")
					.addClass("success")
					.html("Data saved successfully")
					.fadeIn('slow')
					.delay(3000)
					.fadeOut('slow');
				}
				else
				{
					$("#status")
					.addClass("error")
					.html("Error, data could not be saved")
					.fadeIn('slow')
					.delay(3000)
					.fadeOut('slow');
				}
			}
		});
	});

The above code gets the data from the #editable and posts to the send.php file. If the data is posted successfuly, the PHP file recieves the data and inserts to database. If the data is stored in database successfully, then it should return 1. In that case we can display the success message in the #status. Otherwise we can display error message.

The contents of PHP file:

<?php
	$content = $_POST['content']; //get posted data
	$content = mysql_real_escape_string($content);	//escape string	

	$sql = "UPDATE content
			SET text = '$content'
			WHERE element_id = '1'
			";

	if (mysql_query($sql))
	{
		echo 1;
	}

?>

The above PHP code receives the data and updates in the database table, content.

As you noticed, I had added some static text in the #editable div in the HTML code above. But since, we are updating the text in the database, therefore, instead of displaying the static data in our div, we should be fetching the data from database and display in it.

<div id="editable" contentEditable="true">
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select text from content where element_id='1'");
$row = mysql_fetch_array($sql);
echo $row['text'];
?>
</div>

Thats all. You can view the demo or download the complete code below. In the demo, no any changes are being saved in the database. So you would not be able to see changes after page refresh.

  • Pingback: 40 Best Web Design And Development Tutorials From September 2011

  • Alexander Thornade

    Super post! Just like your blog professionalism! Keep up the good work.

  • Richi

    Me encanta!

  • Masoudmanson

    This was awesome.
    Thank you for sharing
    :-**

    Masoud

  • Madia

    Thank you! It’s working. :)

  • http://www.facebook.com/rajneeshgautam Rajneesh Gautam

    awesome . . . .

  • Pingback: CSS Pop-up menu | Aristidesrr

  • Rita2010

    mysql_fetch_array(): supplied argument is not a valid MySQL result resource

    • http://gazpo.com Sami

      Your SQL query is failing. Is your database totally empty? If so, add a row in database.

  • Bg

    Thanks

  • Nnamdi

    this is cool, thanks man. but how can i extend this to involve many other text fields for different other text. pls help sir. my emailaddress is nnamdi2005@yahoo.com. plsssssssssssss

    • Guest

      He is providing a tutorial not his services for your custom needs…. Nice tutorial, very useful.

    • http://twohourblogger.com Martyn Chamberlin

      It’s not that hard man. Take this code:

      $(“#save”).click(function (e) {
      var content = $(‘#editable’).html();
      $.ajax({
      url: ‘save.php’,
      type: ‘POST’,
      data: {
      content: content
      },

      To add other fields, just add variables and declare them in the ajax function. For example, let’s say you had a div in your HTML called #editable_two. It would look like this:

      $(“#save”).click(function (e) {
      var content = $(‘#editable’).html();
      var content_two = $(‘#editable_two’).html();
      $.ajax({
      url: ‘save.php’,
      type: ‘POST’,
      data: {
      content: content,
      content_two: content_two
      },

      Then you can use the $_POST method in the save.php page to grab that additional data. Make sense?

  • Ashkshort

    Thanks, very useful. How could you do it for more than one text area with multiple different ids?

  • http://www.facebook.com/aynamohol Samrat Khan

    How to one more field?

  • Chiragd121

    superb. . .i like it mch

  • Pingback: A Showcase of HTML5 Tutorials for Web Designers

  • http://misamarillasw.com/ Manuelcelemin

    Thankssssssssssssssssssssssssssssssssssssssss

  • Itep Dj

    Very nice tutorial, but how to alter textarea to select box

  • Pingback: 10 Fresh And Useful HTML5 Tips, Techniques And Tutorials

  • Betwinsouls

    Would you be able to do an explanation on how to connect this to a database.
    Thank you.

    • http://gazpo.com Sami

      Just create a database table
      ‘content’ with two fields ‘element_id’ and ‘text’. Add one row in the
      database with element_id 1 and some text.

      • Betwinsouls

        Thank you Sami, really appreciated.