HTML5 In-line text editing and storing to database

September 28, 2011 HTML5, jQuery, PHP 55 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?

      • mcmc

        si i cant get it..can u explain further?

      • mc

        sir..im sorry for spammung but i relly cant get your code..im a newbie in this and my boss wants me to do it..and im promgramming blind here.pls help

        • http://gazpo.com Sami

          Just download the tutorial files from the link above and test it on your server.

      • Robert Visser

        Hi. How should $sql = “UPDATE content SET text = ‘$content’ WHERE element_id = ’1′ “; be modified to enable saving to multiple fields both within the same mysql table as well as different tables? Thanks.

  • 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.

  • http://www.facebook.com/profile.php?id=1536172986 Ali Ben Messaoud

    Can you save to DB onBlur ??

  • Nang

    How are line breaks stored in the database?

  • Miguel Cubias Caceres

    Thanks for sharing your knowledge! :D

  • Lee

    Nice Tutorial, I have it working with a number of text areas which works fine. My only contention is when a user submits after the status update states complete the flashing cursor still appears on that selected element… Which by now does not have the submit/save box. This could mean users (most notably dumb users) will think they can add to that element. Anyway after submitting the cursor does not blink? Im not too great with js.. thanks Lee

  • bp

    Great tutorial, just have one problem with it – when I edit and submit the data is being put to the database but with excess whitespace. Has anyone else had this problem? I’ve further edited the code so it might just be a problem that I’ve caused but any help would be great.

    • Ali

      I’m having the same problem. But I’ve put a temporary solution into place which trims the whitespaces through trim() function in php. Not sure if this would cause others problems ahead but for now it’s working fine.

  • sibor94

    Thank you man how can we replace the element_id=1 with a variable.

    • http://gazpo.com Sami

      just look for some example of mysql_query.

  • craig

    Hi, Awesome script – what confuses me is that I get the error: “An error occured, the data could not be saved” when despite this, the data is successfully saved in the database table. Have I missed something?

  • de

    great tutorial! everythng works fine.

    i just have one problem.

    to select that data from the table which is shown in the editable field i have to collect the user id from a url parameter(its passed in from a telefon software from somewhere else):

    it looks like this
    http://www.localhost/test.php?contact=12345

    so icatch out the user id 12345
    with

    $s = $_GET['contact'];

    and then i put it in here:

    select user from clients where id = $s

    this works fine.

    but i have no success doing the same with the save.php file.
    This is simply getting no variables from the main php file.

    any ideas?

    thanx!

    • Ron

      Did you resolve this? I have the same issue

      • Ron

        Solved. The script cannot do both a post and a get. Need to add to the url:/link?s=+

  • Ron

    Thanks! Things are working great except I cannot update specific id’s in the database.

    I would like to update a specific id. I try to pull it down from the url from url ex http://www.abc.com/af?id=12345

    converting the id=12345 into $id=$_GET['id'] and using the $id variable in the
    mysql query:

    UPDATE tablename set column=’$content’ where column2=’$id’;
    but this does not seem to work. Any advice?

    • http://gazpo.com Sami

      Do you get some mysql error?

      • Ron

        No error. It just does not input the data into the database. If I directly put the id number it correctly works.
        UPDATE tablename set column=’$content’ where column2=’100′;

        It just does not seem to accept it when I use the $id variable.

        $content = $_POST['content']; //gets the posted content
        $var_id=$_GET['id'];
        $content = mysql_real_escape_string($content); // escape string
        $sql=”update variant_list set hgvs_genomic = ‘$content’ where variant_id=’$var_id’”;
        if (mysql_query($sql))
        {
        echo 1;
        }

        It just does not save.

        Thanks again for your help. I’ve been struggling for awhile to get this working.

        Ron

        • http://gazpo.com Sami

          You can start checking if you are getting the id correctly, and then you can print the mysql_error to see whats the problem.

    • Evgeny[Russia]

      IT IS WORKS!
      in index.php:
      url: ‘save.php?id=’+

      in save.php:
      $sql = “UPDATE content SET text = ‘$content’ WHERE element_id = ‘$id’ “;

      GOOD LUCK!

      • Evgeny

        url: ‘save.php?element_id=’+

  • Raju

    This was Awesome, thanks for sharing and i need a little help i want to make a page for resume and i want to edit it when i need like this but i need to make the letters bold and to increase size, and i want this for admin only
    can u help me in this

  • saranya

    useful post :)

  • michaelst

    how do I set up the database to save to?

  • http://twitter.com/Harthacanute1 Harthacanute

    This is really good (thank you) – but how to I get this to work with more than one editable field on the same page? I have the html part as an include file which is repeated five times, displaying data from an sql table. However, only the first of the five can be edited. Sorry if it’s an obvious question … I’m quite new to all of this.

  • edner

    Thank you very much for this very wonderful tutorial………..

  • tim lopes

    Hi there is it possible to do the same without saving to the database but saving the file itself? meaning, if I add the editable to a div in my index.php, but I want it to save the changes done/made to the file within the same file.

  • steve

    I have an issue with my tag getting changed. can i stop the editor from changing html?

  • mhasan

    Everything works fine except this: my data contains html tags. for example: my edited text. How do I remove those tags. By the way, I am using ckeditor; so when I click inside the div, ckeditor pops up. I appreciate you effort. Thank you.

    • Jono

      You could also use strip_tags (php) or regex (php & javascript) but both aren’t great for parsing html for something like removing tags.
      Both of the above ways would work for small amounts of code with some tinkering to get it right.
      What is below should work though (did for me)
      ——————————————————-
      add after var content = $(‘#editable’).html();

      stripHTML(content);

      this can go anywhere though.

      function stripHTML(){
      var re= //g
      for (i=0; i<arguments.length; i++)
      arguments[i].value=arguments[i].value.replace(re, "")
      }