Use your left/right keys to browse tutorials
jQuery and PHP inline editing

jQuery and PHP inline editing

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on November 10, 2009

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


Recent shares

More tutorials from Papermashup
Comments
14 discussions around jQuery and PHP inline editing
  1. chachkalica says:

    jesus…great work, always wanted to make something like this…! :]

  2. nice tutorial, great job man.
    visit http://www.leaneveryday.net for asp.net and jquery tutorials.

  3. Noj says:

    Can i changed the textarea to textfield???

  4. Putra says:

    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.

  5. amarushakur says:

    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

  6. Chris says:

    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="”>

  7. Thomas says:

    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) {

  8. Thomas says:

    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.

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

  10. Enatom says:

    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.

  11. Davinder says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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



Looking for a registry cleaner to speed up your PC and show a full diagnostics?

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.