简体   繁体   中英

save data in editable dynamic html table

I have created editable dynamic html table, on double click over a text the user is able to change it but the change is temporary, i wish to save it in database also.

My code for table is ( @jsfiddle )

html table

<table class="editableTable table table-striped table-bordered">
<thead>
    <tr>
        <th> A </th>
        <th> B </th>
        <th> C </th>
        <th> D </th>
    </tr>
</thead>
<tbody>

    <?php
    $sql=" SELECT * from orderid";
    $result = mysqli_query($con, $sql);
    if(mysqli_num_rows($result)>0)
        {
            while($row = mysqli_fetch_assoc($result))
                {?> <tr>
                        <td> <? echo $row['a']; ?> </td>
                        <td> <? echo $row['b']; ?> </td>
                        <td> <? echo $row['c']; ?> </td>
                        <td> <? echo $row['d']; ?> </td>
                    </tr>   
                <?}
        }?>

</tbody>
</table>

script code

 $(function () 
        { 
            $("td").dblclick(function () 
                { 
                    var OriginalContent = $(this).text(); 
                    $(this).addClass("cellEditing"); 
                    $(this).html("<input type='text' value='" + OriginalContent + "' />"); 
                    $(this).children().first().focus(); 
                    $(this).children().first().keypress(function (e) 
                        {
                            if (e.which == 13)
                                {   
                                    var newContent = $(this).val(); 
                                    $(this).parent().text(newContent); 
                                    $(this).parent().removeClass("cellEditing"); 
                                } 
                        }); 
                    $(this).children().first().blur(function()
                        {
                            $(this).parent().text(OriginalContent); 
                            $(this).parent().removeClass("cellEditing"); 
                        }); 
                }); 
        });

code i wish to use to edit the entry is

$sql1="UPDATE tablename set A='".$a."', B= '".$b."', C= '".$c."', D= '".$d."' WHERE id='".$id."' ";
if(!mysqli_query($con,$sql1))
    {
        die('Error:' . mysqli_error($con));
    }

table view

id  A  B  C  D
1   a  b  c  d

Can anyone please tell me how i can save the new entry in database

Here is a working (at the client) jsfiddle example .

I fix you a remove class problem, $(this) was the input and by doing $(this).parent().text("") then $(this) does not exist to get his parent again.

So you can print your table like this

<tr data-id="1"><!-- Include here the row id -->
    <td data-name="a"> a1 </td><!-- Include each cell's name -->
    <td data-name="b"> b1 </td>
    <td data-name="c"> c1 </td>
    <td data-name="d"> d1 </td>
</tr>

I added you a save function

    var saveChanges = function(cell){
        $.ajax({
            type: 'POST',
            url: 'save_changes.php',
            dataType: "json",
            data: getData(cell),
            success: function (json){
                if(json.error){
                    console.log('Error : '+json.error);
                }else{
                    console.log('Data saved.');
                }
            },
            error: function(){
                console.log('Can not connect to the server.');
            }
        });
    }

And a get data function

var getData = function(cell){
    var data = {
        "id" : $.trim(cell.parent().data('id')), // Get row id
        "name" : $.trim(cell.data('name')), // Get the tuple name
        "value" : $.trim(cell.html()) // Get new value
    };
    return data;
}

On the server you need a php file to save the data, the code should be something like

    // Server Code
    // file "save_changes.php"

    // SQL injection protect
    // http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html
    function sanitize($data){
        // remove whitespaces (not a must though)
        $data = trim($data);

        // apply stripslashes if magic_quotes_gpc is enabled
        if(get_magic_quotes_gpc()){
            $data = stripslashes($data);
        }

        // a mySQL connection is required before using this function
        $data = mysql_real_escape_string($data);

        return $data;
    }

    if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["value"])){
        $id = sanitize($_POST["id"]);
        $name = sanitize($_POST["name"]);
        $value = sanitize($_POST["value"]);
        // Save Data
            // Here you save your data
            $sql1="UPDATE tablename set '".$name."'='".$value."' WHERE id='".$id."' ";
            if(!mysqli_query($con,$sql1)){
                echo '{"error":"'.mysqli_error($con).'"}';
            } else {
                // Report ok
                echo '{"status":"success"}';
            }
    } else {
        echo '{"error":"missing data"}';
    }

Be carefull with the spaces, i added some $.trim() to remove them. If new content is the same with the old, no change will be send to the server, you may want to disable it.

 $(function() { var getData = function(cell) { var data = { "id": $.trim(cell.parent().data('id')), "name": $.trim(cell.data('name')), "value": $.trim(cell.html()) }; return data; } var saveChanges = function(cell) { $.ajax({ type: 'POST', url: 'save_changes.php', dataType: "json", data: getData(cell), success: function(json) { if (json.error) { console.log('Error : ' + json.error); } else { console.log('Data saved.'); } }, error: function() { console.log('Can not connect to the server.'); } }); /* // Server Code // file "save_changes.php" // SQL injection protect // http://www.bitrepository.com/sanitize-data-to-prevent-sql-injection-attacks.html function sanitize($data){ // remove whitespaces (not a must though) $data = trim($data); // apply stripslashes if magic_quotes_gpc is enabled if(get_magic_quotes_gpc()){ $data = stripslashes($data); } // a mySQL connection is required before using this function $data = mysql_real_escape_string($data); return $data; } if(isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["value"])){ $id = sanitize($_POST["id"]); $name = sanitize($_POST["name"]); $value = sanitize($_POST["value"]); // Save Data // Here you save your data $sql1="UPDATE tablename set '".$name."'='".$value."' WHERE id='".$id."' "; if(!mysqli_query($con,$sql1)){ echo '{"error":"'.mysqli_error($con).'"}'; } else { // Report ok echo '{"status":"success"}'; } } else { echo '{"error":"missing data"}'; } */ } $("#myData td").dblclick(function() { var OriginalContent = $.trim($(this).text()); $(this).addClass("cellEditing"); $(this).html("<input type='text' value='" + OriginalContent + "' />"); $(this).children().first().focus(); $(this).children().first().keypress(function(e) { if (e.which == 13) { var newContent = $(this).val(); var cell = $(this).parent(); cell.text(newContent); cell.removeClass("cellEditing"); if ($.trim(newContent) != OriginalContent) saveChanges(cell); } }); $(this).children().first().blur(function() { var cell = $(this).parent(); cell.text(OriginalContent); cell.removeClass("cellEditing"); }); }); });
 .editableTable { border: solid 1px; width: 100% } .editableTable td { border: solid 1px; } .editableTable .cellEditing { padding: 0; } .editableTable .cellEditing input[type=text] { width: 100%; border: 0; background-color: rgb(255, 253, 210); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myData" class="editableTable table table-striped table-bordered"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr data-id="1"> <!-- Include here the row id --> <td data-name="a">a1</td> <!-- Include each cell's name --> <td data-name="b">b1</td> <td data-name="c">c1</td> <td data-name="d">d1</td> </tr> <tr data-id="2"> <!-- Include here the row id --> <td data-name="a">a2</td> <!-- Include each cell's name --> <td data-name="b">b2</td> <td data-name="c">c2</td> <td data-name="d">d2</td> </tr> </tbody> </table>

$("#save").click(function () {
    var dataA='Data in A td';
    $.ajax({
        type: 'POST',
        url: 'your php page where you do the insert',
        dataType: "json",//response from php page
        data: {
            dataA: dataA//data you will save in database
            },
        success: function (data) {
            alert("Success");
        },
        error: function (data) {
           alert("Error");
        }


    });
});

You can do it like this. Just change the url of the php page then you can also change the dataType into what ever you want the php page to respond example are text and html and more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM