How to save and retrieve contenteditable data

31,743

Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.

Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.

Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:

jsFiddle Demo

$('.editable').prop('disabled',true);

$('.editbutt').click(function(){
    var num = $(this).attr('id').split('-')[1];
    $('#edit-'+num).prop('disabled',false).focus();
});

$('.editable').blur(function(){
    var myTxt = $(this).val();
    $.ajax({
        type: 'post',
        url:  'some_php_file.php',
        data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
    });
});

PHP file: some_php_file.php

<?php 
    $myVar = $_POST['varname'];
    $secondVar = $_POST['anothervar'];
    //Now, do what you want with the data in the vars

Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxt variable -- I added that to show how you would add a second var of data to the ajax.

Here are some basic examples to bring you up to speed on ajax:

AJAX request callback using jQuery


There is no short path to learning jQuery or AJAX. Read the examples and experiment.

You can find some excellent, free jQuery tutorials here:

http://thenewboston.com

http://phpacademy.org


UPDATE EDIT:

To respond to your comment inquiry:

To send data from a DIV to a PHP file, first you need an event that triggers the code. As you mentioned, on an input field, this can be the blur() event, which triggers when you leave a field. On a <select>, it can be the change() event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.

So, the user clicks a button -- you can get the content of the DIV using the .html() command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:

How to send DIV content after a button clicked:

HTML:

<div class='big_wrapper' contenteditable>
    PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />

jQuery:

$('#mybutt').click(function(){
    var myTxt = $('.big_wrapper').html();
    $.ajax({
        type: 'post',
        url:  'some_php_file.php',
        data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
    });

});
Share:
31,743

Related videos on Youtube

Samuël Visser
Author by

Samuël Visser

Updated on July 09, 2022

Comments

  • Samuël Visser
    Samuël Visser almost 2 years

    I want to be able to change the text of some pages. Using contenteditable would be perfect for me.
    Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.

    This is how I would like it to work:

    1. Admin hits a button 'edit'
    2. div becomes editable.
    3. When the admin is ready editing, he hits a button 'save'
    4. The data is saved to a file or database (don't really know what would be the best option).
    5. The edited content shows up when the page is opened.

    This is all I have for now:

    <div class="big_wrapper" contenteditable>
      PAGE CONTENT
    </div>
    

    I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
    My problem is that i really have no idea how to save the edited data.
    I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.

    Thanks for your help,

    Samuël


    EDIT:

    @gibberish, thank you so much for your super-quick reply!
    I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.

    Here's my code:
    over_ons.php:

    <div class="big_wrapper" contenteditable>
      PAGE CONTENT
    </div>
    
    <input type="button" value="Send Data" id="mybutt">
    
    <script type="text/javascript">
      $('#mybutt').click(function(){
        var myTxt = $('.big_wrapper').html();
        $.ajax({
            type: 'post',
            url:  'sent_data.php',
            data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
      });
    });
    </script>
    

    sent_data.php:

    <?php
     session_start();
    include_once('./main.php');
    include($main .'connectie.php');
    
    $tekst=$_POST['myTxt'];
    
    $query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";
    
    mysql_query($query);
    ?>
    

    Thanks again for your great help!
    Can you also help me to make the div editable only when the user hits a button?


    SOLUTION:

    It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
    I would like to share how i did this if someone wants to do the same.

    over_ons.php:

    //Active page:
    $pagina = 'over_ons'; ?>
    <input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
    //Active user:
    if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
    $editor = $_SESSION['gebruikersnaam']; ?>
    <input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php  
    } ?>
    
    <!--Editable DIV: -->
    <div class='big_wrapper' id='editable'>
        <?php
            //Get eddited page content from the database
            $query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
            while($inhoud_test=mysql_fetch_array($query)){
                $inhoud=$inhoud_test[0];
            }
    
            //Show content
            echo $inhoud;
        ?>
    </div>
    
    <!--Show edit button-->
    <?php
    if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
    {?>
        <div id='sidenote'>
            <input type='button' value='Bewerken' id='sent_data' class='button' />
            <div id="feedback" />
        </div>
    <?php }
    

    As this is a pretty long and complicated file, I tried to translate most of my comments to english.
    If you want to translate something that in't already translated, the original language is Dutch.
    javascript.js:
    //If the system is in edit mode and the user tries to leave the page,
    //let the user know it is not so smart to leave yet.
    $(window).bind('beforeunload', function(){
    var value = $('#sent_data').attr('value'); //change the name of the edit button
    
    if(value == 'Verstuur bewerkingen'){
        return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
    }
    });
    
    //Make content editable
    $('#sent_data').click(function(){
        var value = $('#sent_data').attr('value'); //change the name of the edit button
    
        if(value == 'Bewerken'){
            $('#sent_data').attr('value', 'Verstuur bewerkingen');  //change the name of the edit button
            var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
            $div.prop('contenteditable',!isEditable).toggleClass('editable')
            $('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
        }else if(value == 'Verstuur bewerkingen'){
                    var pagina = $('#pagina').val();
                    var editor = $('#editor').val();
                    var div_inhoud = $("#editable").html();
                    $.ajax({
                    type: 'POST',
                    url:  'sent_data.php',
                    data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
                    success: function(data){
                    Change the div back tot not editable, and change the button's name
                        $('#sent_data').attr('value', 'Bewerken');  //change the name of the edit button
                        var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
                        $div.prop('contenteditable',!isEditable).toggleClass('editable')
                        
                    //Tell the user if the edditing was succesfully
                        $('#feedback').html(data);
                        setTimeout(function(){
                            var value = $('#sent_data').attr('value'); //look up the name of the edit button
                            if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
                            $('#feedback').text('');
                            }
                            }, 5000);
                        }
                        }).fail(function() {
                        //If there was an error, let the user know
                            $('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
                        });
        }
    });
    

    And finally,
    sent_data.php:
    <?php
    session_start();
    include_once('./main.php');
    include($main .'connectie.php');
    
    //Look up witch page has to be edited
    $pagina=$_POST['pagina'];
    //Get the name of the person who eddited the page
    $editor=$_POST['editor'];
    //Get content:
    $tekst=$_POST['tekst'];
    $tekst = mysql_real_escape_string($tekst);
    
    $query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
    
    }
        if(mysql_query($query)){
            echo "<p class='opvallend'>Successfully saves changes.</p>";
        }else{
            echo "<p class='opvallend'>Saving of changes failed.<BR>
            Please try again.</p>";
        }
    ?>
    
  • Samuël Visser
    Samuël Visser over 9 years
    I have been trying to learn jQuery and AJAX by following totorials. I learned that the blur event only works on input fields. And i don't want a input field, but a div. What is the best way to sent data from the div to the php file? By the way, in your example you make a input field editable with a button. I tried a lot of things to get the div to be only editable when hitting a button, but couldn't make it work. For me it is also OK to just use PHP for making the div editable, but maybe it's simple with jQuery and maybe you can explain me how to make a div editable with a buton in jQuery?
  • Samuël Visser
    Samuël Visser over 9 years
    I got the part with making the div editable after hitting the button done now, just with PHP and a form like i am used to use. The only thing now is to make that 'sent data' button work, and actually sent the text in the div to the php file. (BTW, I tested the PHP file without using jQuery, and it does work. So I know for sure the data is not sent to the PHP file yet, if it is the data will be in the database)
  • cssyphus
    cssyphus over 9 years
    Please, please, please... Read my full answer above carefully. Try it. Then, try each of those AJAX links - experiment a bit. I promise, you would have everything done in about 45 minutes (allowing 30 mins for learning/testing) and you will be very happy with the end result. You have been working on this problem for many hours now -- what have you got to lose?
  • Samuël Visser
    Samuël Visser over 9 years
    I don't really understand why, but adding <script src="ajax.googleapis.com/ajax/libs/jquery/1.11.1/…> to the code made it work. I saw people using it on YouTube, but they didn't explain why. Thanks you so much for all your help, I really appriciate it!!
  • cssyphus
    cssyphus over 9 years
    Yes, you need that because $('class_or_id'). syntax is jQuery -- any time you see that, the code is jQuery -- so you need to load the jQuery library. The three linked examples showed that also. Check out these Free jQuery Tutorials -and- Free Register&Login Tutorial -- I learned tons from them myself.
  • osullic
    osullic almost 4 years
    This doesn't do what the OP wants. msSaveBlob is also non-standard and obsolete. Not to mention the code is unreadable. I would recommend skipping this answer.