How to save and retrieve contenteditable data

99封情书 提交于 2019-11-30 12:20:53

问题


I want the admins from my website to be able to change the text of some pages. Using contentediteble 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 for me, 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 edditing, 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>";
    }
?>

回答1:


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
    });

});



回答2:


You could save the whole page clientside with this:

    <script>
function saveAs(filename, allHtml) {
allHtml =  document.documentElement.outerHTML; 
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;        
document.body.appendChild(elem);
elem.click();        
document.body.removeChild(elem);
}
}    
</script> 

hth



来源:https://stackoverflow.com/questions/25790268/how-to-save-and-retrieve-contenteditable-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!