Edit In Place with AJAX Using jQuery Javascript Library
14 June 2006 | Tutorials | 47 Comments
I originally saw a version of this concept on Quirksmode and then a more Web 2.0-ish version on the 24 Ways site.
I’m going to show you two ways that you could use jQuery to accomplish the same effect, or better.
The Goal
An AJAX (or AHAH) proof-of-concept page that allows the visitor to edit the very (x)HTML page they are viewing, without leaving the page.
The Concept
Click the text to be edited and magically a textarea appears with buttons beneath to save or cancel the changes. Changes are sent via AHAH to a PHP script which normally would be used to update a database (MYSQL or flatfile).
The Demonstration
In this first demonstration, I’m using a div with an id of editInPlace. When you roll your cursor over the div, the background changes to a pale yellow. Clicking the text will start some DOM (Document Object Model) magic resulting in the div being replaced by a textarea input — with the text to be edited inside.
Clicking the save button will send the new HTML over to a simple PHP script that does nothing more than print out the data it receives (via $_POST).
In a real world application you would add in some additional safety checks, and then update your database with the new information and send back information that tells jQuery if the changes were successful.
But in this example, all changes are successful, the same information sent to the PHP script comes back to the jQuery code and is show in a simple window alert.
Explanation
The way I kick things off should be very familiar by now. Remember, if you don’t want to use the jQuery document.ready function then feel free to throw in your own init() function.
$(document).ready(function(){
setClickable();
});
So the first thing that happens is that the setClickable() function is fired. This function does the following:
Looks for the div with id=”editInPlace” and tells jQuery to do something when the div is clicked.
function setClickable() {
$('#editInPlace').click(function() {
Grabs the html inside the div using jQuery’s html() function. This html is wrapped inside of some more html that will make up the textarea and buttons for save and cancel.
var textarea = '<div><textarea rows="10" cols="60">'+$(this).html()+'</textarea>'; var button = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL" class="cancelButton" /></div></div>'; var revert = $(this).html();
The same html found within the div with id=”editInPlace” is assigned to a variable called “revert”. This will be used in the event the cancel button is used.
var revert = $(this).html();
jQuery’s DOM function “after” is used to place this new textarea html after the div we’ve targeted. I immediately chain another method to this (to save space) and tell jQuery to remove the div.
$(this).after(textarea+button).remove();
Using jQuery, I target the save and cancel button by using their class names. I instruct jQuery to trigger my final function “saveChanges” when either button is clicked. I close out the function that tells jQuery what to do when the div is clicked, but I do not put an apostrophe at the end because I want to chain more methods onto this div.
$('.saveButton').click(function(){saveChanges(this, false);});
$('.cancelButton').click(function(){saveChanges(this, revert);});
})
I chain a simple mouseover and mouseout to my code which tells jQuery to add and remove a class when a cursor rolls over the div we’ve targeted (id=”editInPlace”).
.mouseover(function() {
$(this).addClass("editable");
})
.mouseout(function() {
$(this).removeClass("editable");
});
};//end of function setClickable
Function “saveChanges” will take the button object for the first variable and the cancel variable should either be false or contain the html I stored in the “revert” variable.
function saveChanges(obj, cancel) {
If “cancel” is false then I’m telling this function to save the changes by sending the html over to the php script. I grab the html within the textarea by using some of the DOM functions available through jQuery: parent() and siblings().
if(!cancel) {
var t = $(obj).parent().siblings(0).val();
DOM basics are beyond the scope of this tutorial, but I’m basically telling jQuery “The obj (save button) has a parent (a div)… go find it. This object has one or more objects on the same level of the DOM tree… I want the first one. And grab the value of that object.”
(On second thought… if you aren’t familiar with DOM style of coding, then my explanation probably didn’t make much sense to you. I suggest Googling “DOM javascript” or something similar.”)
This html is assigned to the “t” variable and now it’s time to send it via POST over to test2.php.
$.post("test2.php",{
content: t
},function(txt){
alert( txt);
});
}
If cancel has a value, then it should be html stored originally in the “revert” variable. So, at this point, I want the “t” variable to be set to the original html.
else {
var t = cancel;
}
The next step is to use the DOM functions within the jQuery javascript library to place a new div, with the “editInPlace” id, after the div containing the textarea… and then remove the div containing the textarea.
$(obj).parent().parent().after('<div id="editInPlace">'+t+'</div>').remove() ;
In a nutshell, this tells jQuery “Go backwards on the DOM branches two moves. Place this HTML after the object found at that location, and then remove the object.”
Finally, we call the setClickable function again and close out the saveChanges() function. The purpose of recalling the setClickable() function is to reset the onMouseover, onMouseout, and onClick events.
setClickable(); }
Second Example
The second one is very similar but a little more complex.
Instead of one large div, this example turns every P tag into its own editable region.
The difficulty comes when you want to send the data to a server side script and target the correct P tag for updating in the database.
The solution I came up with is to number each P tag and send this information over to the PHP code. What you see in the alert box is that the PHP code “knows” which P tag is to be changed.
Known Issues
If you used something similar in a real application then you’d want to verify that the changes were made before telling jQuery to update the DOM with the new html.
For this demonstration there is no interaction with a database and so I skipped this step.
Technorati Tags: javascript, AJAX, AHAH, jQuery, DOM, scripting
Subscribe
47 Comments
Leave a Reply
You can follow the discussion through the Comments feed. You can also pingback or trackback from your own site.






Having written something similar to this
http://joseph.randomnetworks.com/tag/editinplace
One the things that people pointed out what problems dealing with edits where you delete all of the text. That was something that I’d only recently addressed (version 0.2.1).
Your demos seem to be returning an error when trying to save an empty string. There is also no way to go back and edit again once the empty string is saved.
Joseph,
I saw your site after I had already started the jQuery code for this tutorial.
The code in my php script is set to throw an error if $_POST[’content’] is empty or null. This could easily be addressed in the javascript, or the PHP code, or both. I’m not really concerned about it — but glad you pointed it out.
This is really more a “proof of concept” than “ready to use code you just plug into your website”.
But I do appreciate the feedback.
Joseph,
I went back and tinkered, saw what you were referring to… and made the change.
Very simple addition of one line to my code, and a slight modification to the PHP.
lots of sites use some sort of template markup, and just editing the HTML would not be allowed. Maybe you could extend the article just a bit more where you do an ajax call to the server first to get the templated markup.
Wesley,
At first I didn’t understand what you were suggesting, but then I remembered that a lot of CMS systems require/use template tags which have no meaning outside the template system itself.
Quick plug: my upcoming CMS does not force you to learn template tags.
Second point is that this demonstration doesn’t interact with a database at all. I’ve left it up to you to modify it as you see fit.
That said, if I have time today I’ll consider putting up an example that illustrates your point. I’m sure you’ve already figured out how to do it, since it’s not very complicated.
Another question would be, how to convert the textarea to a full-fledged WYSIWYG editor (using an opensource component like tinymce) Are there any problems with it? Will all button images be reloaded every time I edit the paragraph (IE images bug)
Just wanna say that I’ve been trying to get into a bit of AJAX or more accurately AHAH for some projects im working on for a while
But scriptaculous and other libraries I’ve read have the WORST manuals/tutorials ever
I’ve just read through your site and its been incredibly easy to understand
Thankyou
Phil,
You’re welcome. Thank you for the compliment.
Like the simplicity of it, however I found an error in second example. Here are the steps to replicate:
1) open paragraph 3 editable field and make changes, but do not save;
2) open paragraph 2 editable field and make changes, but do not save;
3) save paragraph 3 editable field. gets two popups instead of one.
4) save paragraph 2 editable field.
After this you can no longer edit the lower paragraph. Seems to also apply to 2 then 1, and also 3 then 1 as well. However it doesn’t seem to have any problems if you open in top to bottom order. I didn’t test all 3 paragraphs at the same time in various orderings.
Any ideas why this is happening?
I’ll have to take a closer look. In the meantime, I suppose you’re better off using the other example I provided.
Or make it so when you change to edit mode for one item, it disables the ability to open the other editable items until you save the current entry.
Haha, I can’t believe it. I was searching for a sort of thing like that (like the ready-to-edit descriptions of flickr) to use on a gallery page I am doing and couldn’t find anywhere, so I figured how to do it myself (using a mix of regular js, jQuery and ASP). Then, when I am finally done (after weeks of struggle, because I am such a newb on all of this), I find your script, and it’s so much better that it almost made me cry, hahaha.
Good work on this one, I hope I can use it on a next project.
This is handy, well written Jack. Looking forward to your CMS. Do you know of anyone who has taken this to the next level and got the data in/out of MySql? Could you give us some pointers?
Keep up the great work.
Rob
Sure. In the function saveChanges you’d likely use ajax to post the data to a file that can (1) read the data (2) verify that it’s legit (3) save to a database (4) respond with an error or success message.
With jQuery I’d recommend the $.post method. See my tutorial on AJAX with jQuery and the information on the jQuery website.
The real tricky part with the edit in place code that edits individual p tags is that the database script would need to either find the specific p tag and replace it… or more likely, you’d send over ALL of the editable regions and have the database script replace the entire entry…
I don’t know if that last part made much sense the way I wrote it.
I know you’d like to have a prewritten snippet but it’s just not something I have time to whip up right now. I have a lot of projects I’m juggling, including the cms.
I hope my answer points you in the right direction and if I get time to write up some code for the database part, I might do so.
Also, see the jQuery plugin for edit in place at
http://www.dyve.net/jquery/?editable
I just looked at the code and it’s a lot fancier than mine.
$(document).ready(function() {
$(".edit_inline").editable("post.php", { saving:"<img
src=’img/indicator.gif’>", extraParams:{id:42} });
});
Where post.php is the database interaction file. id=42 could be an extra variable to verify the post is legit (you’d need to tweak this a bit to improve security).
The only think that i don’t like about this is that it only uses the p tag…
what if you give a span the class/id of editInPlace… when you click save or cancel it will put the paragraph tag back in the DOM instead of the span tag, or whatever else you decide to use?
My question is, how do you find out what the original element was??
Dave,
Here… check out this plugin. It might be closer to what you’re looking for:
http://www.dyve.net/jquery/?editable
It’s a bugg if you open all three then press cancel in demo.php.. you can not open the middle open
Is it possible to get fckeditor or any other rich text editor in place of textarea for edit inplace
Please let me know if have a tutorial on it
Regards,
Ritesh
No need to reinvent the wheel:
http://jquery.com/docs/Plugins/tinyMCE/
Also a ton of plugins for edit in place (most of which I believe were released after this tutorial, but not because of it, AFAIK)
http://docs.jquery.com/Plugins
thanks for the script, it works well. I am wondering how to pass additional parameters to the PHP file in the POST? Say that I have a field with a hidden value I would like to pass this. I know its part of the $.post but Im not sure how to get that value from the HTML file.
Please advise
With regards to my previous post Im trying to get the value as follows in JS:
$(”input”).val(”hidden”)
but doesn’t seem to be correct perhaps someone can guide me on that? Thanks in advance.
jquery has a form submit with ajax plugin that you should check out. Go to the main jquery.com website and view the plugins, it’s one of the official ones.
Jack, you are a patient man! Thanks much for taking the time to put together this tutorial. Nice stuff.
Jack, please help. I am using inline edit for my application but I ran into 2 problems:
1) If use type in the long message it will display offscreen to the right(with the scroll bar) how can i format the result into a fix width. I tried to enclose within div tag or table but it has problem
2) After user type in message i want to put in pre tag just to avoid user put in some code example continuous popup how can i do that?
Have you tried any of the plugins on the jQuery page?
http://www.dyve.net/jquery/?editable
http://www.appelsiini.net/~tuupola/javascript/jEditable/
http://joshhundley.com/my-work/teditable-in-place-editing-for-tables/
http://davehauenstein.com/blog/archives/28
[…] Edit In Place with AJAX Using jQuery Javascript Library - Javascript Tutorials - 15 Days Of jQuery (tags: jquery edit_in_place ajax javascript elangdell) […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
There´s some point that was leaved behind. When you back the text if the people cancel the edit, the dom is updated and loss the events, so you just could click and edit once, when you call the function of cancel, it has to reattach the event of click to work well…
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Edit in Place with Ajax using jQuery. […]
[…] - edit in place plugin for jQuery. jQuery editable.jQuery Disable Text Select Plugin.Edit in Place with Ajax using jQuery.jQuery Plugin - Another In-Place Editor.TableEditor.tEditable - in place table editing for jQuery. […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
hi. i searched whole internet about inline editing and the title “Edit In Place With Ajax 2″ helped me the much.but you havent been share the test.php. i am searching inline editing code that helps me to make multiple edit in place operation and have contacted with database. i know php well but i am new in ajax. at least could you share the test.php? thank you. i tried to do my own but it didnt work
www.fubace.com/adminpan
Jit,
I’m about to do a site redesign and update of the tutorials, with code available.
Hi,
My problem is just the same as “Jit”,
So I’m looking forward for the site redesign.
However, I’d like to read and write the contents of the editable fields from external files - as an alternative method to the MySQL-database …
Have been messing around, trying to code that thing myself, but still without a usable result …
( -: roland :- )
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Edit in Place with Ajax using jQuery […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Edit In Place with AJAX Using jQuery Javascript Library (tags: jquery) […]
[…] Jeditable - edit in place plugin for jQuery jQuery editable jQuery Disable Text Select Plugin Edit in Place with Ajax using jQuery jQuery Plugin - Another In-Place Editor TableEditor tEditable - in place table editing for […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
[…] Jeditable - edit in place plugin for jQuery. jQuery editable. jQuery Disable Text Select Plugin. Edit in Place with Ajax using jQuery. jQuery Plugin - Another In-Place Editor. TableEditor. tEditable - in place table editing for […]
xdvdsfvd fdgsd
fdsaiuwa dfgdsgfs