jQuery Edit In Place (JEIP)

History

A few years back I wrote a Javascript library for editing content in place, that was based on Prototype. It was modeled after the Flickr UI/approach. Nothing amazing, but it worked well enough.

Fast forward a few years and the momentum in the Javascript library field has moved decidedly to jQuery. I’ve been meaning to write a port of the edit in place code to use jQuery, and now I finally have. To help confusion with the original code I’m calling it jQuery Edit In Place, or JEIP for short.

Downloads

Current Version: 0.1.2 (Change Log)
Download: jeip.js

Demo

I’ve put together a very basic demo. Everything is done with templates and CSS classes, so if you don’t like the default look of the demo there are lots of methods for changing it.

Examples

Here’s the most basic example, it enables in line editing for the page element that has an id of content.

$( "#content" ).eip( "save.php" );

After editing is complete and the user clicks on the save button the script sends the url, form_type, element id, original value and new value data via HTTP post to save.php. The returned data is expected to be in JSON object, with the following values: is_error, error_text and html. The is_error field is a boolean, and error_text is used to provide information about the error condition. The html is a string that is used to replace the contents of the edited element.

If you’ve got a larger chunk of text to edit you’ll want to use a textarea form:

$( "#content" ).eip( "save.php", {
    form_type: "textarea"
} );

And for those cases where you just need to provide options, there’s an easy way to do a select form:

    $( "#content" ).eip( "save.php", {
        form_type: "select",
        select_options: {
            blue    : "Blue",
            green   : "Green",
            red     : "Red",
            black   : "Black",
            brown   : "Brown",
            white   : "White"
        }
    } );

For select forms two additional bits of data are passed to the save URL: the original option text and the new option text.

The eip function will also work on multiple elments, so if you select a class it will make all of the elements with that class editable:

    $( ".edit-class" ).eip( "save.php" );

The Save XHR and Response

When the edit form is saved JEIP uses the jQuery AJAX function to send data to the save URL. It send the following fields via HTTP POST:

  • url – (string) URL that the edit form was on.
  • form_type – (string) The type of edit form that was used (text, textarea, select)
  • id – (string) The id of the DOM element that was edited.
  • orig_value – (string) The original value of the DOM element that was edited.
  • new_value – (string) The new value of the DOM element that was edited.
  • data – (object) Optional additional data that was passed along via the original eip call.

For select form edits two additional fields are sent:

  • orig_option_text – (string) The original option display text.
  • new_option_text – (string) The new option display text.

The response to the XHR needs to be a JSON object with three values:

  • is_error – (bool) When true indicates that there was some sort of error when the save URL processed the XHR. Under normal conditions this should be set to false.
  • error_text – (string) When is_error is true, this string is used to provide a plain text descriptive of what the error was.
  • html – (string) This string is used to replace the old value of the edited DOM element.

Options

There are a number of options that can be provided as part of the second parameter in the eip function. The defaults should fit for most, but if you want to tweak things I’ve tried to provide lots knobs.

  • save_on_enter – (bool) When true the save event is triggered when the enter key is pressed. Doesn’t apply for textarea edits.
  • cancel_on_esc – (bool) When true the cancel event is triggered when the escape key is pressed.
  • focus_edit – (bool) When true give the edit field focus when the edit form is shown.
  • select_text – (bool) When true select the text in the edit field.
  • edit_event – (string – event) What type of event (usually click or dblclick) to trigger the edit mode.
  • select_options – (object) Key/value pairs for the option fields in a select form. The key will be used as the option value and the value from the option will be used as the display option text.
  • data – (object) Additional data that will be passed in the XHR to the save URL.
  • form_type – (string) What type of edit form to use: text, textarea and select. The default is text.
  • size – (int) Value to use for the size attribute on the edit field. By default this is calculated at run time.
  • max_size – (int) Maximum value to allow when calculating the size value.
  • rows – (int) Value to use for the rows attribute in textarea edit forms. By default this is calculated at run time.
  • max_rows – (int) Maximum value to allow when calculating the rows value.
  • cols – (int) Value to use for the cols attribute in the textarea edit forms.
  • savebutton_text – (string) Text to use on the save button.
  • savebutton_class – (string – CSS class) CSS class to use on the save button. The default value is jeip-savebutton.
  • cancelbutton_text – (string) Text to use the on the cancel button.
  • cancelbutton_class – (string – CSS class) CSS class to use on the cancel button. The default value is jeip-cancelbutton.
  • mouseover_class – (string – CSS class) CSS class to apply when the mouse enters an element that is editable. The default value is jeip-mouseover.
  • editor_class – (string – CSS class) CSS class to apply to the edit form wrapper. The default value is jeip-editor.
  • editfield_class – (string – CSS class) CSS class used on the edit field element. The default value is jeip-editfield.
  • saving_text – (string) Text shown while the XHR is waiting for a response. The default value is ‘Saving …’.
  • saving_class – (string – CSS class) CSS class used on the saving_text string. The default value is jeip-saving.
  • saving – (string – template) Template string used to show the saving_text string.
  • start_form – (string – template) Template string used to start the edit form.
  • form_buttons – (string – template) Template string used to show the form buttons.
  • stop_form – (string – template) Template string used to end the edit form.
  • text_form – (string – template) Template string used to show the text edit forms.
  • textarea_form – (string – template) Template string used to show the textarea edit forms.
  • start_select_form – (string – template) Template string used to start a select edit form.
  • select_option_form – (string – template) Template string used to show options elements in select edit forms.
  • stop_select_form – (string – template) Template string used to edit a select edit form.
  • after_save – (function) Function that is called after the XHR completes. By default it just flashes the element a few times.
  • on_error – (function) Function that is called when the save URL returns an error (by setting is_error to true in the return JSON object). By default it calls the alert() function to show the error_text returned from the XHR.

178 Responses to jQuery Edit In Place (JEIP)

  1. Brad says:

    Wonderful! I’d love to take a look at an example save.php, as well – this is exactly what I’ve been looking for!!!

  2. Franciz says:

    How can I add an onBlur function that cancel the form??

    P.S.: Sorry for my bad english

  3. Franciz says:

    Don’t worry, already done it adding inside “_editMode” funcion:

    $( “#edit-” + self.id ).blur( function( e ) {
    _cancelEdit( self );
    } );

    P.S.: I almost forgot to congratulate you for the script… it’s just great.

    • Joseph Scott says:

      Hmmm, perhaps I should make than an option. I would probably default that feature to being disabled though, I think many would find having their edit field disappear because they clicked somewhere else more frustrating than helpful.

  4. Christian says:

    Great plug-in! I was actually just looking for something like this a couple of weeks ago, but the only solution I could find was quite specialized and wouldn’t fit my needs. I’m glad I did another quick search today and came across your work :)

    Just as an aside, I was wondering if there is an easy way to trigger an edit from an event tied to another element. For example, have a button beside the editable field that says ‘Edit’ and have it trigger the edit when clicked.

    Thanks again for contributing your work!

  5. Christian says:

    Thanks for the quick response!

  6. David L says:

    Hi!
    Seems like a wonderful jQuery plugin…
    I’ll try to implement it in my project :)
    just one question – is it possible to implement it without the AJAX save feature?
    I only want to use it to change text fields, and handle the save myself submitting the whole page

    Thanks for your work!

  7. Pat Hatchel says:

    Great plugin! But, I’ve written a local application, that doesn’t care anything about send data to a server, but only saving on the local machine. Can this plugin be adapted to this scenario?

    • Joseph Scott says:

      How does your app save data locally? I’d imagine if there’s a Javascript interface to where you are storing data (like Google Gears) then you could adapt the code to send updates there instead.

  8. Thanks for the useful script. I’m trying to implement it in a WordPress blog so that I can make post and page edits on-the-fly. Seems like everything is working though it doesn’t save. Instead, it says “Saving…” then the text vanishes. I assume it’s the JSON.php which I fetched from the PEAR site. Could you make JSON.php example available for a look over?

    Thanks!!

  9. Pingback: jQuery Edit in Place | webtoolkit4.me

  10. Tim says:

    Is it possible to handle the case that the editable div is empty? For now, I could not edit at all.

    Thanks.

  11. Paul says:

    I want to use your inline routine to edit a label under a thumbnail from a set of thumbnails on a horizontal filmstrip, update the page to show the new entry, then send that new entry to a database to update for later viewing. I do not have access to run .PHP on the system I am with. I can use C# and JavaScript. Does your routine offer the ability to run a function instead of running the SAVE.PHP file?

    • Joseph Scott says:

      It just sends the data to a URL, so you can use any server side language, PHP just happens to be the one I used. The response needs to be JSON encoded, which isn’t specific to a particular language either. I suspect most languages have a library for encoding/decoding data in JSON.

  12. marvin says:

    Thanks for your great work on this plug-in. Was wondering, how can I specify a string which will be displayed for the empty string? Something like “Click Here to Edit”.

  13. Shane says:

    just a quick question I’m hoping you can help me out with…I have everything set up as seen on this site…everything seems to be working except that the data doesn’t get switched…it just stays on the “saving…” part and only if I refresh does it show the new data in its place…not sure if its the JSON file that isn’t properly functioning or if there is something else I’m missing…do I need PEAR running to use the JSON file?

    I love the plugin…just hoping I can get it to work…

    • Joseph Scott says:

      First thing I’d do is debug on the server side and make sure that your script is getting the data correctly. If that then look at the response you script is sending back and make sure that it looks correct.

  14. Shane says:

    k…well I got it figured…
    Thank you soooo much for this awesome plugin…

  15. Rob says:

    I can’t understand when I try this on my own server, when I click save, the icon gif displays, but it never disappears and saves the text that I just typed! Help?

  16. Rob says:

    Sorry for lack of explanation…I mean to say… the data does not save.

    • Joseph Scott says:

      Two things to look at when debugging this, first make sure that your script is getting the request and the correct data. If that’s working then make sure that your script is returning the correct data, JSON encoded, etc.

  17. Tom Shafer says:

    Hi, How would i make use of this if I had multiple divs that needed this, yet only calling it once, ie…

    data
    data
    data

    I would think i would have jeip call from the class and use the id to reference the div. Is this functionality in place now?

    These are created using jquery and are inserted on the fly and are coming from the database on page load.

    Thanks,

    -TOM

  18. Tom Shafer says:

    The last comment diddn’t show my full message

    ie…
    div id=”div_1″
    div id=”div_2″
    div id=”div_3″

  19. Tom Shafer says:

    How could I pass additional data to eip from within the editing div. Lets say I have a extra attribute like this

    div extra=”home” I need to pass something like this so that only a section in the database where page = home is updated.

    Thanks

    • Joseph Scott says:

      To send additional data when the save event happens take a look at the ‘data’ option. This doesn’t gather up attributes from the element, but it does allow you send what arbitrary data as part of the save XHR.

  20. Jason says:

    I’m trying to use the ‘data’ option, but I’m having trouble getting it to respond. I’m putting the values into data in key/value pairs:

    data: {key : 'value'}

    and I’m trying to read it in my php with:

    $var = $_POST['key'];

    Is this not the structure I should use?

    • Joseph Scott says:

      Go back and take a look at the documentation on this page, under the section indicating what fields are sent in the XHR. The ‘data’ field is called ‘data’ in the POST.

  21. Jason says:

    Ok, I think I’ve solved my problem. I ended up using this jquery-json plugin, which I then modified my lines to look like this:

    data: $.toJSON({key1:"value1", key2:"value2"})

    and

    $data = json_decode(stripslashes($_POST['data']));

    This places it into a PHP object of $data->key1. If you do the following line it will place it into an array of $data['key1']:

    $data = json_decode(stripslashes($_POST['data']), true);

  22. Nick says:

    Wanted to thank you for an EXCELLENT plug-in. It came highly recommended, and has not disappointed.

    I’m trying to implement some client side validation prior to transmitting the new value, and potentially triggering an alert box if it fails.

    Is this something that has been addressed or considered?

  23. Evan says:

    Would it be possible to show how to add custom input types? I am looking to attach the jquery datepicker to a text field containing a date value. In other words, when the text field is clicked on, the jquery date picker will show to select a date which will then fill the text field.

    • Joseph Scott says:

      I hadn’t really thought about it that way, but you could probably do that by overriding the default form templates. Take a look at the ‘text_form’ variable, it’s the template that’s used when editing a simple string. You can override it when calling .eip() on your element and provide the datapicker hooks inside the form.

      Let me know how that works out, would make an interesting example for others who want to do something similar.

      • Evan says:

        I was able to add a new datepick_form to the jeip.js, and hooked it in from a separate js file.

        I am now struggling to bind the datepicker jquery function to the text field created by jeip.js.

        For example, i may have a field (id=’field_A’) and when jeip is called, it replaces it with id=’edit-field_A’. Since the new field is not created until that point, what do you recommend I do to bind the datepicker function to that new field after its creation by jeip.js?

        This is day 2 for me playing with jquery, so I apologize for the questions and if I am not being clear.

        • Joseph Scott says:

          My guess is you’ll need a way to re-bind the datepicker code to the id/class of the form field because it’s added dynamically to the page later on. The other possibility is that the datepicker code needs to watch for new fragments being added to the page to see if it needs to bind events to them. Don’t know if there’s anything other that supports that right now.

          What the mostly likely leaves us with is having to adding something to JEIP that can optionally call user defined functions after each editing event.

          • Evan says:

            I managed to get a date picker field working and figured I would pass on the info if you wished to add it. Plus it might prove useful for others looking to dynamically add/bind functions to jeip.

            In this example I used jquery datepicker and livequery to get it working as intended.

            In my javascript that is called as part of the document.ready loading I used live query to bind to a new class. Example:

            $(“.jeip-datefield”)
            .livequery(function(){
            $( this ).datepicker({ showOn: ‘both’ });
            });

            In my javascript that binds jeip to my fields I wish to edit, I forced it to use a new form_type. Example:

            $( “#datefield” ).eip( “save.php”, {
            form_type: “datepick”
            });

            In jeip.js I changed the following:

            1. Added a new class:

            editdate_class : “jeip-datefield”,

            2. Added a new form template:

            datepick_form : ‘ ‘

            3. Added a new form field:

            if( opt.form_type == ‘datepick’ ) {
            form += _template( opt.datepick_form, {
            id : self.id,
            editdate_class : opt.editdate_class,
            value : value
            } );
            } // date form

            And I think that is it.

            I use jquery ajax to query a database and return a form through php. On the success of the ajax response, I call a function that binds eip to the new fields returned from php. The livequery allows me to then trigger the datepicker in the newly inserted fields.

            Hope this helps and wasn’t too confusing.

            Evan

          • Joseph Scott says:

            Yep, livequery was what I was thinking of. At some point I’ll try out the datepicker + jeip with your changes and see where this needs to go.

          • Ashish says:

            Hello Joseph
            Have you implemented this functionality in latest update?
            If yes,where can I find that.
            I need the same functionality.

            Thanks
            Ashish

    • Juan Pablo says:

      Where did you place the third part of modifications of JEIP?

      3. Added a new form field:

      I’m very interested in your jeip.js source code, because i’m coding same functionality of JEIP and datepicker.

      Thanks in advance!

  24. Mike says:

    Thanks for all the great information. We use JQuery and PHP on the custom web pages for our customers.

  25. PSS says:

    Excellent script!

    I’m a jQuery newbie but loving it already!

    I needed to restrict text field length to X characters, and obvious way to do it is to burn it into code

    text_form : ‘ ‘,

    How can I make maxlenght=”250″ a setting?

    Also, there is a class “missing” in

    form_buttons : ‘…

    I added

    and with

    .jeip_buttons {
    position: relative;
    float: left;
    margin: -50px 0px 0px 0px;
    }

    placed buttons above text input.

    • Joseph Scott says:

      If you just want to include the maxlength=’250′ into the form then I’d suggest including a new form template with the .eip() call.

      Ahh, you want to move just the form buttons around with CSS. Sounds reasonable.

  26. Dan Sorensen says:

    Awesome implementation! :-)

    Could there be a way to unbind/suspend ‘eip’ from a selector?

    It would be nice to enable and disable ‘edit in place’ depending on what else is happening on the page.

    Clicking to edit is USUALLY intended, but if I’m moving blocks around a page it interferes. I’d like to have a button that would toggle between the sortable and edit in place functionality. Sortable can be bound and unbound. This looks close…

    I’ll look into it some more…

  27. chocula says:

    Get looking script, I am just trying to get around it (This is my first look into javascript really!) This would be perfect for what I need however is it possible to use this if you have variable text items on a page? For example (my data is retrieved dynamically) My PHP displays a list of names of people (which need to be editable) Obviously this list is ever changing. You mentioned above that you could use a .edit-class but then when it comes to updating the data of the MySQL table (your save.php) how would you be able to make sure you update the right table and row as wouldn’t it just pass the value of the first class? Sorry if that doesn’t make sense, I am kind of banging my head together

    • Joseph Scott says:

      You need to make sure that there was a unique ID for each element that you are making editable. You could do this by having your PHP script generate a unique ID attribute value for instance.

  28. Dan Sorensen says:

    Chocula: I agree with Joseph. To expand upon his point, on the server side, I would put the table and row id (or a suitable mapping), into the class or id.

    Examples:
    class=”edit-class students” id=”1234″
    It would take some fancy javascript to retrieve the info and pass it back to the server, but it’s entirely possible.

    class=”edit-class” id=”students_1234″

    using .split(‘_’) on the id, you’ll be able to retrieve both students (table) AND 1234 (id). You should be able to do something similar on the server side, which would probably be better.

  29. Ben May says:

    Great Script- thanks heaps

  30. Javier Montanov says:

    How can I have a simple link to activate the edit, for example:

    TEXT TO EDITClick here to Edit

    I want to edit the text inside the span “text-edit” from the link “link2Edit”. Thanks.

  31. Bart says:

    I’ve implemented the alternative edit-in-place plugin called ‘Jeditable’ (http://www.appelsiini.net/projects/jeditable) but because it lacks some basic features (like hover effect) I decided to drop it and look around for a similar plugin. Now I’ve bumped into JEIP and I wonder what the advantages are over Jeditable. Joseph, did you look into that plugin? If so, what are your findings?

  32. Anthony says:

    Do the save and cancel button HAVE to be under the text box, or can then come after the textbox (like in your drop down box example)

  33. Nick says:

    What I’m trying to do is click a button (say, an edit button) and all the fields a certain class become editable and automatically go to their editable state.. so, in other words, I have a table, I want to click Edit on the side of a row and all the columns in that row become editable immediately (not once you mouseover the individual text in that column and click it). Is this possible?

    • Joseph Scott says:

      Certainly possible, though there’s no specific code to do that in one action in jeip.

    • Jon Thomas says:

      Exactly what I want to do. I have several elements I’d like to make editable by clicking one button. Then, I’d like to have one Save/Cancel button for all. I would also like the option to bypass submitting to server, and use my own form “save” button to submit all at once when I’m done editing several objects. Anyone know of anything that does this?

  34. Alex says:

    Hey, this is an amazing script and I thank you for it greatly.

    There’s just one thing that I can’t quite get to work, and that is viewing the edited content right away.

    The way I have it working, is I put some logic into the save.php to update a mysql database. And it works.

    However, I need to manually refresh the page after editing to view the changes made.

    I believe a similar problem was posted above on December 5th. The edited area just remains stuck on “Saving…” until I manually refresh. And if I keep clicking save, it creates a string of “Saving…Saving…Saving…” and cancel just shows the initial value as well, even though it actually has been changed in my database.

    I’m pretty new to this stuff, so please bare with me :P

    Thanks,
    Alex

    • Joseph Scott says:

      Double check to make sure that your script is returning the properly formatted JSON response. I suspect that if the Saving… never goes away then the reply for the XHR either didn’t happen or it didn’t get back what it expected to.

      • Alex says:

        Thanks for the reply Joseph.

        After some toiling about and learning more about XHRs I wondered how to put the value I needed into the JSON response. I then re-read the instructions at the top of this page and realized that I needed to put the response into the html = “” at the bottom of save.php. I replaced the “” with $new_value and it works perfectly now :) (though there is a bit of a delay that I wonder if I can shorten…but that might be server lag.)

        Oh, and just looking through JEIP.js I stumbled across something on line 67 that might be a typo. In the class for the start_select_form it is: editfield_clas which might need that second s. :)

        Again, huge thanks :)
        Alex

        • Joseph Scott says:

          You’re right, definitely a typo there. I’ll fix that and make sure it gets into the next version. Guess I’ll need to make a next version one of these days then :-)

        • Brent says:

          Alex -

          I am also trying to use JEIP to update a mysql database. I have JEIP working great with static text, but I’m having difficulty getting it to update my database. If you could post an excerpt of your version of save.php to allow for updates to a database, I know that I (and possibly others) would appreciate your insight. Thanks in advance.

          Joseph -

          Great script and excellent instructions for all us n00bs out there! Thank you.

  35. Hi Joseph,

    This is very useful stuff.
    I just wanted to know if its possible to validate my component before ajax request is sent to the server. I mean to say i want to check on the client side if the the text is empty or not and prevent from sending data to the server if the text is empty.

  36. Ege says:

    IS THERE NO SUPPORT FOR EMPTY STRING (like click here to edit) ?? Very Bad…

  37. Steve K. says:

    Hi Joseph!
    Thanks for this awesome plugin! I’m currently considering using it to allow a user to update particular sections of a single page by wrapping certain content in editable divs which change to textboxes on click, which I assume jeip will do.

    I’m wondering: If I have more than one of these editable areas on the page, is there a way I can disable all of the other areas while the current one is clicked so that a user can only edit one at a time, and then re-enable all of them again on a submit of the current area?

    Much thanks, sir!

  38. AndoNeo says:

    Nice job. Looks great. I managed to get it happening only to find it won’t work with my repeating regions. About the third time I’ve found this problem.

    So I have a php loop that brings a value in for multiple records in the database and I want to be able to edit each one of these using this. It seems only the first field will be editable. Anyone have any thoughts why?

    Thanks

  39. AndoNeo says:

    Joseph,

    Thanks for the reply. Here is the example of your script deployed on a repeating region. The first item in the list works. Editing that is. I haven’t linked to the back end yet. Do you think it’s possible to have it function in lists?

    http://reconarcade.com.au/testing/jqueryedittest.php

  40. reymond buenaviaje says:

    Hello there!
    this is a great plugin… i was wondering where do i get JSON.php?

  41. ninja says:

    can i create without json in save.php
    what a variable was send to save.php
    and what a variable i can send back to html with JEIP

    maybe can you create a sample… hehe…
    :) sory for my english…

    • Joseph Scott says:

      You can use anything your want to process the data, as long as returns the expected JSON response. Take a look at the examples, it’s pretty basic to make this work with any back end code.

  42. Andrew says:

    Hi there, this script is awesome thanks! Does exactly what I need. Although I am running into the following error: window is null
    withinElement()()jquery-latest.js (line 2869)
    proxy()()jquery-latest.js (line 2762)
    handle()()jquery-latest.js (line 2693)
    (?)()()jquery-latest.js (line 2468)
    [Break on this error] try { parent = parent.parentNode; } ”

    Any ideas what this means?

  43. Esteban Vicario says:

    Hi Joseph, first of all… excellent script! :)

    Now I begin to describe what my problem.
    In my page I have 2 dropdownlist edit in place make with library.
    When page load both dropdownlist load great, now I want to change the value of the dropdownlist 2 depending on what is selected in the dropdownlist 1

    when dropdown 1 is created in the option after_save I call another function. This function rewrite the dropdownlist 2 with your library, but the old values can not replace with new values, there is some way to reset what is above and write again from the beginning?

    (sorry for my poor level of English)

    Regards.

  44. AndoNeo says:

    I’m making good progress with your code Joseph but I seem to have run into another issue that you may be able to suggest a way forward on.

    Numbers with a period (or decimal point as we refer to it in Aus) in them appear to be erroring out the code.

    I can get the values to alert and appear in the firebug console but they don’t seem to be getting through jquery into the database. I had a look at the offending lines from the firebug report but I couldn’t see anything I understood to be a problem.

    Firebug is giving me this response.

    data is null
    anonymous()jeip.js (line 304)
    success()jquery-1….6.min.js (line 29)
    anonymous()jquery-1….6.min.js (line 28)
    [Break on this error] if( data.is_error == true ) {\njeip.js (line 304)

  45. ile says:

    Hi Joseph,
    I tried two “edit in place” scripts from two authors and as far as i can see only your “version” has what I need. BUT, I dont even manage to install it. I think problem is in save.php file. I saw your save.php file but there is some JSON.php file to be required, which isnt mentioned here, actually it isnt mentioned where to download it from (if neccessary). I’ve managed to come to this point:
    When I click on text, input field and buttons appear but when subbmitting there is no effect.
    I read comments from other users and I saw that few have the same problem as I do:
    - How to apply editing to a particular content which is loaded from database. On page, there are many records displayed, each has its own id. Can you please explain more detail how to solve this problem.
    I know how to display id and content values, but where to “put” id and how to process it via POST method to save.php
    Thank you in forward!

    Regards,
    Ile

    • Joseph Scott says:

      The response to the XHR needs to be in JSON format. Modern versions of PHP5 have built in JSON functions, the JSON.php is a pure PHP version that does essentially the same thing. If you are having errors in the request you need to make sure the response is being received by the browser. Firebug in Firefox is helpful for this.

      The element ID is sent as part of the XHR so you don’t need to do anything extra to get that.

  46. mr vrx says:

    Hi Joseph, how to change this sctipt to get select_options from ajax in:
    form_type: “select”,
    select_options: ?
    Regards.

  47. David says:

    the script works great, except when i am using ajax elsewhere to load the div containing the editable fields, then they arent becoming editable — it works the first time, but not after the refresh. ive tried using jquery.live to bind the function permanently but it doesnt work … am i missing something?
    thanks!

    • Joseph Scott says:

      Did you try eip() again after the AJAX’ed in DIVs have been added?

      • David says:

        actualy i think i got it working by putting a seperate $(document).ready() on the ajax page (the one being re-loaded) and puttnig the eip in there. but other than that, im not sure how to do it from the main page or the main js include. just ends up making my code ugly (the random javascript call ends up being in the middle of the file) but if thats the only way to do it …

  48. James says:

    Hi Joseph, this is a plug in that I was looking for. I have used it sometime and liked it very much. Now I am implementing a another program that has a table with 2 columns. First colums is version number of a software and second column is the target date to release the software. For example:

    Version Number
    Target Date

    1.0
    2007-09-30

    The contain of the table will be dynamically insert so no way I will know the id of any beforehand. In the javascript file I have the code:
    $( “tbody td” ).eip( “save.php”,{ select_text: true } );
    When I click on the first cell of a row, the two cells of that row just merge into one and the first cell disappeares.
    Do you know how to go about to fix that?
    Thank you.

  49. James says:

    Hi Joseph, it is me again. Thank you for your promt answer last time. This time I have another question. I have a form which has a table:

    Version Number
    Target Date

    I also have a javascript function which will dynamically populate the table tbody with data. I dont have problem to use jeip.js with data of the first column. But with the second column after I edit it, it display new value outside of the table. If I edit it the second time but hit cancel button, it moves back to the right place. Do you know how to make new edited data not jumping around?

    Thank you in advance.

  50. Brian says:

    Im getting a blank data area after i save it. I input the data, the saving thing comes up and then it goes away and the new data never shows up. What am i doing?

    This is my save.php file im using

    encode( array(
    "is_error" => false,
    "error_text" => "Ack! Something broke!",
    "html" => ""
    ) ); ?>

    and this is my JSON.php code

    self::$maxRecursionDepthAllowed) {

    throw new Zend_Json_Exception(
    "Function _processXml exceeded the allowed recursion depth of " .
    self::$maxRecursionDepthAllowed);
    }

    if ($recursionDepth == 0) {

    $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
    }

    if ($simpleXmlElementObject instanceof SimpleXMLElement) {

    $copyOfSimpleXmlElementObject = $simpleXmlElementObject;

    $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
    }

    if (is_array($simpleXmlElementObject)) {

    $resultArray = array();

    if (count($simpleXmlElementObject) $value) {

    if(($ignoreXmlAttributes == true) && (is_string($key)) && ($key == "@attributes")) {
    continue;
    }
    $recursionDepth++;
    $resultArray[$key] = self::_processXml ($value, $ignoreXmlAttributes, $recursionDepth);

    $recursionDepth--;
    }

    if ($recursionDepth == 0) {

    $tempArray = $resultArray;
    $resultArray = array();
    $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
    }

    return($resultArray);
    } else {

    return (trim(strval($simpleXmlElementObject)));
    }
    }
    }

  51. Rob says:

    Hi Joseph,
    Thank you very much for this, it is very well explained, cleanly written and hence easy to use.
    :) Having said that………
    Two quick questions
    Is it possible to do multiple selects?
    ” ” ” ” ” checkboxes or radio buttons?
    If not, I will still use your script on text fields and simple selects, but it would be brilliant to have those as well :)

    Best,
    Rob

  52. Xaos says:

    Hello,
    just wanted to say thank you for a wonderful script and ask something about a small problem I have.
    Everything works find including a dynamically populated select form I’m using in my pages except that the field with the select doesn’t get highlighted when you put the mouse over it, although clicking and editing works perfectly.
    Am I missing some option?
    The code is like this :
    $( “#physical_rack_” ).eip( “admin/modify.php”, {
    form_type: “select”,
    select_options: {

    }
    } );

    which generates something like this :
    $( “#physical_rack_1472″ ).eip( “admin/modify.php”, {
    form_type: “select”,
    select_options: {
    1 : “1″,
    10 : “10″,
    11 : “11″,
    12 : “12″,
    18 : “18″
    }
    } );

    Again thank you for the time you devoted to this project

    • Xaos says:

      I just noticed I forgot to use the correct tag and the code that’s being displayed isn’t correct…. here we go again.


      $( "#physical_rack_" ).eip( "admin/modify.php", {
      form_type: "select",
      select_options: {

      }
      } );


      $( "#physical_rack_1472" ).eip( "admin/modify.php", {
      form_type: "select",
      select_options: {
      1 : "1",
      10 : "10",
      11 : "11",
      12 : "12",
      18 : "18"
      }
      } );

  53. Chris Seckler says:

    Hi Joseph,

    I don’t know if you remember, but I had lunch with you at the 2009 SF WordCamp.

    nice looking plugin. In fact, it is exactly what I am looking for for a project I am currently working on. Unfortunately, I am not very familiar with JSON, so I will have to read up on it to figure out how exactly to update my mySQL database with the results in the save.php file.

    One question though. In your demo, the fields themselves don’t update, yet rather it says saving and then it goes blank. Is this because the new changes are now in the save.php file and your demo is not connected to a database?

    • Joseph Scott says:

      JSON is fairly minimal markup for data, PHP and virtually every other language out there has libraries reading/writing JSON data.

      Thanks for pointing out the demo was broken, I’ve fixed it now.

  54. romein says:

    Hi Joseph,

    Thanks for this great plugin! It’s exactly what i was looking for!
    I have a question though. At the text which will be edited, there is a possibility to have an image in it. Currently, when i click at the text to change it, the image is shown as:
    How can we modify it so to show its alt attr (or title attr) ??
    Thanks!

    • Joseph Scott says:

      Not sure exactly what you mean. Do you want to be able to edit the IMG tag when you click on an image?

      • romein says:

        Hi,
        It seems that after the post, a small text was cut.
        Look, when i click at the text (which will be edited), the images are shown as: img src=”" . What i want is instead of showing this (which contains the path of the image) to show only the alt or title attr of each image.
        Is this possible?
        Thanks.

  55. WebDevNYC says:

    If someone needs it, I added fckEditor support and here is how I did it. I have also created a ASP version of the save.php if anyone needs it.


    ========================================
    var opt
    ========================================
    Right Under:
    textarea_form : '#{value} ',

    Add:
    wysiwyg_form : '#{value} ',

    ========================================
    var _editMode
    ========================================
    Right Under:
    // textarea form

    Add:
    //added the fckeditor here with form type wysiwyg
    else if( opt.form_type == 'wysiwyg' ) {
    form += _template( opt.wysiwyg_form, {
    id : self.id,
    value : value
    } );
    } // wysiwyg form

    Right Under:
    if( opt.focus_edit ) {
    $( "#edit-" + self.id ).focus( );

    Add:
    //replace the textarea with fckEditor
    if( opt.form_type == 'wysiwyg' ) {
    var oFCKeditor = new FCKeditor("edit-"+self.id) ;
    oFCKeditor.BasePath = '/fckeditor/' ; //this is the path to your fckEditor Folder.
    oFCKeditor.ReplaceTextarea() ;
    }//end fckEditor

    REMEMBER: change the oFCKeditor.BasePath to the path on your server.

    ========================================
    var _saveEdit
    ========================================
    Right Under :

    var new_value = $( "#edit-" + self.id ).attr( "value" );

    Add the Following Line :

    if( opt.form_type == 'wysiwyg' ) {
    new_value = FCKeditorAPI.GetInstance("edit-" + self.id).GetHTML();
    }

    Replace:

    var ajax_data = {
    url : location.href,
    id : self.id,
    form_type : opt.form_type,
    orig_value : orig_value,
    new_value : $( "#edit-" + self.id ).attr( "value" ),
    data : opt.data
    }

    With:
    var ajax_data = {
    url : location.href,
    id : self.id,
    form_type : opt.form_type,
    orig_value : orig_value,
    new_value : new_value,
    data : opt.data
    }

  56. WebDevNYC says:

    @Joseph Scott could you delete my comments from above. It did not show up correctly. What I did was add support for fckEditor and created a save.asp for people wanting to use this for classic asp and wanted to share it with anyone that might want it.

  57. Tim says:

    I’ve implemented tinyMCE but I’m having a hard time figuring out where the final save result occurs. I need to disconnect the editor when this occurs.

  58. Manni says:

    This is a very nice and useful little script. Thank you!

    I had a hard time figuring out what the data option does and how it’s supposed to be used, though. However, it seems that the backend gets the data as a parameter called data.

    My backend needs several parameters that are needed to make sure the user is authenticated and the backend needs to know which module has to do the processing. Essentially, I needed to have two extra parameters that are posted along with the rest of the data: session_id and node.

    Here’s a little patch that made this possible for me:


    --- jeip.js 2009-12-21 11:42:36.000000000 +0100
    +++ tmp/jeip.js 2009-12-21 11:57:18.000000000 +0100
    @@ -44,6 +44,8 @@
    max_rows : 10,
    cols : 60,

    + extra_params : {},
    +
    savebutton_text : "SAVE",
    savebutton_class : "jeip-savebutton",
    cancelbutton_text : "CANCEL",
    @@ -283,6 +285,12 @@
    ajax_data.new_option_text = $( "#edit-option-" + self.id + "-" + new_value ).html( );
    }

    + if ( opt.extra_params ) {
    + for ( var key in opt.extra_params ) {
    + ajax_data[ key ] = opt.extra_params[ key ];
    + }
    + }
    +
    $.ajax( {
    url : opt.save_url,
    type : "POST",

    I can now make anything editable with a little code that looks like this:


    $( ".editable" ).eip( 'backend.pl', { extra_params: { node: 'Change', session_id: '1234' } } );

  59. Roony Alvarez says:

    Hi there..
    is there any reason why the saving action on asp servers wouldn’t preserve spaces or line brakes?
    Thank you

  60. Luis says:

    I dont undestand de use of the save.php , I’m new using php I dont know where you get these values, I hope you can help me =)
    $url = $_POST['url'];
    $form_type = $_POST['form_type'];
    $id = $_POST['id'];
    $orig_value = $_POST['orig_value'];
    $new_value = $_POST['new_value'];

    if( $form_type == ‘select’ ) {
    $orig_option_text = $_POST['orig_option_text'];
    $new_option_text = $_POST['new_option_text'];

    $new_value = $new_option_text;
    }

  61. Dmitriy Kravchenko says:

    Hi,

    I look a problem.
    My content generated by AJAX request. After generated content append to div, but in browser in source code this content not showing, only visual in browser.

    When content added from AJAX request EIP not working ((( working only if i manualy in file create code

    Can you help me ?

    • Joseph Scott says:

      Perhaps your browser isn’t updating the HTML source view from AJAX requests?

      • Dmitriy Kravchenko says:

        Not updated, all content generated “on fly” i see this content only if using FireBug “Inspect Element”.

        I don’t know how can update physical content in browser document.

        sorry for my English (

        • Dmitriy Kravchenko says:

          Hi, Joseph Scott !

          I found some problem.
          If i click on first time… nothing reaction, but if i click second time and other times.. it’s working )
          It’s first problem.
          Second problem with sending data, i must send to post additional field with my parameters, how can i do this ??

          Thanks.

  62. amarushakur says:

    i am using it in my final year project. my script consists of a table which is displayed by a server side php script. i want to make it possible for users to edit records by just clicking the record and then it turns into an editable field. however, i want the fields to be validated before it is saved into the database. can you please help me with a complete client and php server side script on this. i need it urgently. Please help

  63. kamil says:

    hi there everyone!
    i’ve tried to change the script to update my mysql database but i think i’m pretty noob to do this. i really need an ‘edit-in-place select box’ thing and i can’t convert this to database. can anybody help me with this?
    thanks in advance.
    Kamil

  64. Daniele says:

    Hello Joseph, thx for your support :)

    I would like to see an exemple of usage for the optional data object (data – (object) Optional additional data that was passed along via the original eip call.)

    I unsuccessfully tried:


    data: {
    param1 : "Blue",
    param2 : "Green"
    }

    but the data passed are [object Object]

    How do i pass extra parameters? I need to pass extra parameters to indicate to save.php the data type (text needs ”, int doesnt) and in witch table the data must be saved.

    Now i can do the work using the data object like that:

    data: “tableID-dataType”

    then the save.php will recive via post the parameter data=tableID-dataType and splitting it i make it work.

  65. latehourscoder says:

    Uh, just brilliant … just started to code some xsl + xml monkey business for editing one simple xml document … but this one saved my ass … thank you!

  66. Miles says:

    A couple of changes to allow edit on table cells in-line.

    If you make a td editable then the line
    $( self ).after( form );
    puts the new edit in line field after the end of td which will mess up your table (see posts James 16th & 23 Sep 2009). I didn’t want to use another element [div|span] as they may be empty and thus unclickable.

    A suggested change to options to make things work
    start_form : ”,
    stop_form : ”,

    and add default node_type to the options
    node_type : “span”,

    you can then override the node type from within your jquery call.
    $(‘td.editible’).eip( “/admin/jsasset_admin.php”, {
    node_type: “td”
    } );

    Now your td.editable gets faded out and the new edit field is inserted wrapped in a lovely td. On save or cancel it gets swapped back out.

    Thanks for the plugin Joseph. Nice and compact.

  67. Miles says:

    Doh! Try again
    start_form : ‘>#{node_type} id=”editor-#{id}” class=”#{editor_class}” style=”display: none;”<’,
    stop_form : ‘>/#{node_type}<’,

  68. Deepak says:

    Can I have an example to download? Where can I get the JSON.php file

  69. wanluqman says:

    Deepak,
    JSON.php on my laptop comes with this info

    /**
    * Unit tests for Services_JSON.
    * @see JSON.php
    *
    * @category
    * @package Services_JSON
    * @author Michal Migurski
    * @author Matt Knapp
    * @author Brett Stimmerman
    * @copyright 2005 Michal Migurski
    * @version CVS: $Id: Test-JSON.php,v 1.27 2006/03/02 16:08:06 migurski Exp $
    * @license http://www.opensource.org/licenses/bsd-license.php
    * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
    */

  70. Manni says:

    Is there a way I can dynamically fill in the select options? Depending on which element was clicked to edit?

    I have a page with several entities that can be clicked to edit. Each of these entities features a select box. However, the contents of those select boxes depends on which of the entities is edited.

    So either I let the back-end produce the select options and let it produce different class names or ids for each and provide an extra eip function for each of those. Or I come up with some clever Javascript that does all this dynamically.I just don’t have a clue how I would do that.

    Anyone?

  71. uaint2pac says:

    how do i apply the click event to more than one form element. anytime i try this example $(“#savepres”).click(function(){
    var illness = $(“#illness”).attr(“value”);
    var symptoms = $(“#symptoms”).attr(“value”);
    $.post(“saveprescription.php”,{illness: “”+illness+”",symptoms: “”+symptoms+”"},function(data){
    $(“#showprescription”).html(data);
    });
    });
    $(“#cancel”).click(function(){
    var illness = $(“#illness”).attr(“value”);
    var symptoms = $(“#symptoms”).attr(“value”);
    $.post(“cancelperscription.php”,{illness: “”+illness+”",symptoms: “”+symptoms+”"},function(data)
    $(“#showprescription”).html(data);
    });
    });
    only one of the functions works at a time. if i put them in two different pages they work but not on the same page.
    is there any misunderstanding on how the click event is applied to multiple form elements on the same page? how can i apply the click event to several form elements at a time performing different functions

  72. adam says:

    Was trying to implement this into a HUGE project that I was assigned to, but after failing to understand the data objects (extra info being passed via POST). I had to remove it from the project.

    This would have been perfect though, and I would guess the credit giving from the project would’ve helped too.

  73. tom says:

    hi,

    how can I make code which edit text(txt1) after click on link?

    test test

    click

    function func()
    {
    $( “#txt1″ ).eip( “save.php” );
    }

    what is wrong?

  74. Pingback: Inplace Editing - Fast Gallery | Rapslis Drupal World

  75. Kazim says:

    Very nice example but when I have saved the cahnges and is saved in the database it will not disappear the save and cancel button.

    I am using it in ASP MVC

  76. Kazim says:

    Hi Joseph, thanks for assistance but the problem was that i was returning my Partialview instead of
    return Json(new { is_error = false, error_text = “”, html = formValues["new_value"] });

  77. Eren says:

    Hi Joseph,

    this is really a nice Script but I have problems with JSON because I didn’t work with it until this time. I took your Save.php and try to modify it, so that I can take the variables e.g. $new_value and put it in a mysql_database. But it didn’t work like I imageined. Can you help me in this case ? I want to change the values on the website and save it in a mysql db buti don’t get any of the variables read.

    thanks for your help

    yours

    eren

    • Joseph Scott says:

      I’d focus on making them both work separately (the AJAX and DB), then looking merging the functionality.

      • Eren says:

        thanks for your reply but my question is how can i use that variables because an INSERT INTO or an UPDATE with that variables don’t work :(

        • Joseph Scott says:

          That should be some basic PHP, I recommend making it work as stand alone page and then add in the edit in place functionality. That way you can be sure the basic features, like INSERTING/UPDATING into the database is working correctly, instead of trying to debug multiple things at once.

          • Eren says:

            sorry didn’t work. can anyone help with a small piece of srccode? how do I add eip functionality in my save.php??

  78. Rorian says:

    Would be a Great work if only i could make it work – what about ‘save.phps’ – in first comments “html”=> $new_value is really still missing, ok but even fixit it on localhost i’m getting error Ack! Something broke! (under firebug-console) the same happens on demo here, I assume, that original file (save.php) has got more saving routines? Due to many interested people getting this up to work – could you explain in a example – how this changes can be saved..

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>