jQuery and PHP inline editing

10 November 2009| 10 Comments| Print

Inline editing as it’s known, or being able to edit content directly on a page is a great tool have under your belt. I’m going to run through exactly how it works as well as how to POST the updated text content through to a PHP script for server side processing to put in the database.

The Code

It looks a little complex so i’m going to quickly run through exactly what’s going on.

  1. When you visit the demo page are presented with a block of text. If you hover your mouse over the text you’ll see a little edit icon similar to when you want to edit content on FaceBook.
  2. If the user clicks on the block of code the text is replaced with a form textarea with the option to save or cancel any changes.

EDIT

Now in a little more detail

  • This tutorial uses binding and unbinding. Put in simple terms we can bind a click event to an element. Unbinding releases the click event from the element, simple. In line 9 of the code below we bind a click event to all the elements with a class of ‘inlineEdit’ the event handler is the function ‘updateText’. This means that everytime a div with the class ‘inlineEdit’ is clicked the function ‘updateText’ will be run. The function ‘updateText’ replaces the current text with a textarea.
  • Next we see the save function. This function is only run when the user clicks the save icon. WE basically save the new text in a variable and pass it through to the update.php file. You’ll notice that the loading icon is displayed during the saving process. We also display a message when there is a response from the PHP page. FInally we remove the ‘selected’ class form the element, and then inject the new text that the user wrote in the textarea into the div
  • The cancel function is activated when the element with the class .revert is clicked. This function simply removes the class ‘selected’ as above in the save function, as well as putting the original text in the div.
$(document).ready(function () {

    function slideout() {
        setTimeout(function () {
            $("#response").slideUp("slow", function () {});
        },
        2000);
    }

    $(".inlineEdit").bind("click", updateText);

    var OrigText, NewText;

    $(".save").live("click", function () {

        $("#loading").fadeIn('slow');

        NewText = $(this).siblings("form").children(".edit").val();
        var id = $(this).parent().attr("id");
        var data = '?id=' + id + '&text=' + NewText;

        $.post("update.php", data, function (response) {
            $("#response").html(response);
            $("#response").slideDown('slow');
            slideout();
            $("#loading").fadeOut('slow');

        });

        $(this).parent().html(NewText).removeClass("selected").bind("click", updateText);

    });

    $(".revert").live("click", function () {
        $(this).parent().html(OrigText).removeClass("selected").bind("click", updateText);
    });

    function updateText() {

        $('li').removeClass("inlineEdit");
        OrigText = $(this).html();
        $(this).addClass("selected").html('<form ><textarea class="edit">' + OrigText + '" </textarea> </form><a href="#" class="save"><img src="images/save.png" border="0" width="48" height="15"/></a> <a href="#" class="revert"><img src="images/cancel.png" border="0" width="58" height="15"/></a>').unbind('click', updateText);

    }
});

The PHP

In this example I haven’t added the database connection script. We basically POST the data to update.php and using PHP we echo back the results. You could quite easily add this data to the database.

$text = mysql_escape_string($_POST['text']);
$id = mysql_escape_string($_POST['id']);

echo $text;
// this is where you could add the updated text to the database where the database row id = $id for example.

The HTML

The HTML is simply a list item with the class ‘inlineEdit’ this makes the content of the element editable. The more elements that you add with this class, the more you can edit. notice how i’ve added an id of 1 to the example below. This could be a specific row in a database for example if you have multiple editable elements on a page.

<h2>jQuery Inline-Edit <img id="loading" src="images/loading.gif"/></h2>
Click the text below to edit it.
<div id="response"></div>
<ul>
  <li class="inlineEdit" id="1">Lorem Ipsum....</li>
</ul>

demodownload


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

10 Comments

  • Davinder

    This is amazing, I love all the new ideas you come up with!
    Thank you

  • Enatom

    My web app is virtually being built off this blog… drag & drop ajax sort… will use “username availability” next… will use this post next too. please keep making tuts like these, its a good blog for the average web developer. absolutely invaluable posts.

    I really need to read through all of your old posts, too… but if this blog has RSS I can port all the posts to my Ipod touch i could read them all offline on journies.

  • Ashley

    @Enatom thanks for the feedback! you can easily subscribe to my feed the subscribe link’s at the top and bottom of each page.

  • George

    Great work!

  • Michael Bryan

    The demo adds a quote at the end of the text in your demo at all times.

    $(this).addClass(“selected”).html(” + OrigText + ‘”

    should be

    $(this).addClass(“selected”).html(” + OrigText + ‘

    Not sure if you did it on purpose so something would always be added, just thought I’d point it out.

    Great script by the way.

  • Thomas

    I’m having a little trouble. For some reason the id isn’t being posted to the php script.

    I don’t really know jQuery that well and can’t seem to figure out the problem myself. Any help you can provide would be great.

    Thanks.

  • Thomas

    I finally got it working like I wanted.

    I changed this -

    var data = '?id=' + id + '&text=' + NewText;

    $.post("update.php", data, function (response) {

    to this

    $.post("update.php", { 'id' : id, 'text' : NewText }, function (response) {

  • Chris

    I like this but is it possible to have multiple response boxes for multiple editable areas?

    For example I loop 10 rows of data which works great. I get 10 different boxes I can edit. The only thing is t he response and loading image always show up on the first one on the page. I can’t think of a way to do this?

    The code below is what I loop. Thanks

    <div class="inlineEdit" id="”>

  • amarushakur

    How do i make sure that the edited content is validated before it is saved. i want both a client side and php server side script please. Am using it for my final year project

  • Putra

    A good tutorial, question is what if there are two fields that will be in the edit in the database. Do you have to make two javascript code for each field ?, or with one javascrip code can change the data in each field? Can you can explain it ?, Thanks.

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here