Make Live Editable Table with jQuery AJAX

A live editable table offers a swift and efficient way to update content directly while viewing it, eliminating the need to navigate to separate edit form pages. This user-friendly feature saves valuable time, as users can modify either specific details or entire records seamlessly within the table itself.

To implement this functionality, use jQuery AJAX, which allows for dynamic and interactive data manipulation. In this guide, we’ll explore two distinct approaches to make table columns editable:

1. Using the contentEditable Attribute:
By adding the contentEditable attribute, you enable quick and in-place editing directly within table cells. This method is perfect for scenarios where rapid updates are preferred, as it removes the necessity for additional input elements.

2. Displaying Input Elements on Cell Click:
The second method provides a structured editing experience. Upon clicking a cell, an input element dynamically appears, pre-populated with the cell’s content. This approach is ideal when you desire a more controlled editing process with standardized input.

By the end of this tutorial, you will have gained valuable insights into creating live editable tables, empowering you to build user-friendly interfaces that optimize productivity and engagement. Let’s dive in and explore the limitless possibilities of jQuery AJAX for crafting exceptional and editable tables.

Make Live Editable Table with jQuery AJAX


Table of Content

  1. Table structure
  2. Database Configuration
  3. Using the contentEditable Attribute:
  4. Demo 1
  5. Displaying Input Elements on Cell Click
  6. Demo 2
  7. Conclusion

1. Table structure

Create users table.

CREATE TABLE `users` (
   `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
   `username` varchar(60) NOT NULL,
   `name` varchar(50) NOT NULL,
   `gender` varchar(10) NOT NULL,
   `email` varchar(60) NOT NULL 
);

2. Database Configuration

Create a config.php for the database connection.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

3. Using the contentEditable Attribute:

The contenteditable attribute enables the container to take input values.

HTML –

The code snippet displays a user list in a table format. To enable editing, each cell within the table contains a <div> element with the contenteditable attribute set to ‘true’. This attribute allows users to modify the data directly within the table, providing an editable and interactive user experience.

<div class='container'>
 
    <table width='100%' border='0'>
        <tr>
            <th width='10%'>S.no</th>
            <th width='40%'>Username</th>
            <th width='40%'>Name</th>
        </tr>
        <?php 
        $query = "select * from users order by name";
        $result = mysqli_query($con,$query);
        $count = 1;
        while($row = mysqli_fetch_array($result) ){
             $id = $row['id'];
             $username = $row['username'];
             $name = $row['name'];
        ?>
             <tr>
                 <td><?php echo $count; ?></td>
                 <td> 
                     <div contentEditable='true' class='edit' id='username_<?php echo $id; ?>'> 
                         <?php echo $username; ?>
                     </div> 
                 </td>
                 <td> 
                     <div contentEditable='true' class='edit' id='name_<?php echo $id; ?>'>
                         <?php echo $name; ?> 
                     </div> 
                 </td>
             </tr>
        <?php
             $count ++;
        }
        ?> 
    </table>
</div>

CSS –

.edit{
     width: 100%;
     height: 25px;
}
.editMode{
     border: 1px solid black;
}

/* Table Layout */
table {
     border:3px solid lavender;
     border-radius:3px;
}

table tr:nth-child(1){
     background-color:dodgerblue;
}
table tr:nth-child(1) th{
     color:white;
     padding:10px 0px;
     letter-spacing: 1px;
}

/* Table rows and columns */
table td{
     padding:10px;
}
table tr:nth-child(even){
     background-color:lavender;
     color:black;
}

PHP –

Create a new update.php file for saving the modified content. Read POST values and execute update query.

<?php

include "config.php";

if(isset($_POST['field']) && isset($_POST['value']) && isset($_POST['id'])){
    $field = mysqli_real_escape_string($con,$_POST['field']);
    $value = mysqli_real_escape_string($con,$_POST['value']);
    $editid = mysqli_real_escape_string($con,$_POST['id']);

    $query = "UPDATE users SET ".$field."='".$value."' WHERE id=".$editid;
    mysqli_query($con,$query);

    echo 1;
}else{
    echo 0;
}
exit;

jQuery –

This jQuery code enables content saving for the editable <div> with the class edit. Clicking on the area adds the editMode class to make it editable. Exiting the edit mode removes the class and extracts the field name, value, and ID from the <div> using the id attribute.

An AJAX request sends the data to update.php for processing. Display AJAX response in the browser console.

$(document).ready(function(){
 
    // Add Class
    $('.edit').click(function(){
         $(this).addClass('editMode');
    });

    // Save data
    $(".edit").focusout(function(){
         $(this).removeClass("editMode");
         var id = this.id;
         var split_id = id.split("_");
         var field_name = split_id[0];
         var edit_id = split_id[1];
         var value = $(this).text();

         $.ajax({
              url: 'update.php',
              type: 'post',
              data: { field:field_name, value:value, id:edit_id },
              success:function(response){
                   if(response == 1){
                        console.log('Save successfully'); 
                   }else{
                        console.log("Not saved.");
                   }
              }
         });
 
    });

});

4. Demo 1

View Demo


5. Displaying Input Elements on Cell Click

In the second method, make the container editable using input elements that show when the user clicks on the table cell.

HTML –

Create a table to display user list. Each table cell has a <div> container and an input element that is initially hidden. Upon clicking the <div> container, jQuery displays the corresponding input element, allowing the user to edit the data.

Both the <div> and input element contain the same values to ensure seamless switching between view and edit modes.

<table width='100%' border='0'>
    <tr>
        <th width='10%'>S.no</th>
        <th width='40%'>Username</th>
        <th width='40%'>Name</th>
    </tr>
    <?php 
    $query = "select * from users order by name";
    $result = mysqli_query($con,$query);
    $count = 1;
    while($row = mysqli_fetch_array($result) ){
         $id = $row['id'];
         $username = $row['username'];
         $name = $row['name'];
    ?>
         <tr>
             <td><?php echo $count; ?></td>
             <td> 
                 <div class='edit' > <?php echo $username; ?></div> 
                 <input type='text' class='txtedit' value='<?php echo $username; ?>' id='username_<?php echo $id; ?>' >
             </td>
             <td> 
                 <div class='edit' ><?php echo $name; ?> </div> 
                 <input type='text' class='txtedit' value='<?php echo $name; ?>' id='name_<?php echo $id; ?>' >
             </td>
         </tr>
    <?php
         $count ++;
    }
    ?> 
</table>

CSS –

CSS is similar as in the above example but just added one new class.

.txtedit{
    display: none;
    width: 99%;
    height: 30px;
}

PHP –

The PHP code is similar to the first example there is no change in the code.


jQuery –

Displaying Textbox when the click event triggers on <div class='edit'> and hiding the container.

When the focus out of the Textbox then send AJAX request to save content and hide the Textbox and update the container text before showing.

$(document).ready(function(){
 
    // Show Input element
    $('.edit').click(function(){
        $('.txtedit').hide();
        $(this).next('.txtedit').show().focus();
        $(this).hide();
    });

    // Save data
    $(".txtedit").focusout(function(){
  
        // Get edit id, field name and value
        var id = this.id;
        var split_id = id.split("_");
        var field_name = split_id[0];
        var edit_id = split_id[1];
        var value = $(this).val();
  
        // Hide Input element
        $(this).hide();

        // Hide and Change Text of the container with input elmeent
        $(this).prev('.edit').show();
        $(this).prev('.edit').text(value);

        // Sending AJAX request
        $.ajax({
            url: 'update.php',
            type: 'post',
            data: { field:field_name, value:value, id:edit_id },
            success:function(response){
                if(response == 1){ 
                     console.log('Save successfully'); 
                }else{ 
                     console.log("Not saved.");  
                }
            }
        });
 
    });

});

6. Demo 2

View Demo


7. Conclusion

Enabling live data editing offers a convenient method for users to modify content swiftly. I’ve presented two implementation options, giving you the flexibility to choose the one suitable for your project.

Additionally, in the demonstration, I utilized TextBox elements, but you can adapt other elements such as radio buttons or checkboxes based on your specific needs.

Note – If you have long list of information and you are showing some of them on your table layout, in this case, its better to take the user to edit page to update some other information.

If you found this tutorial helpful then don't forget to share.

25 thoughts on “Make Live Editable Table with jQuery AJAX”

  1. sir i want to create more table data…bt it works only two column.i want to add two more cloun..bt there is not work prpoerly

    Reply
  2. Dear Yogesh Singh,

    I was wondering if you could help. I would like to be able to create new blank rows so we can dynamically add additional records instead of limited to changing existing records. Do you have a tutorial for this or can you offer some guidance? Thank you in advance!

    Reply
  3. Thanks for this great and pratical editable table. I am learning to program in PHP and Ajax and have to thank you very much. Just one question:
    In the update.php, the last line is echo 1;
    What does echo 1 means? Normally, I see that they only close the connection at the end.
    Thank you Yogesh and I hope to get a reply soon!

    Reply
  4. i did an import of csv file and the table is editable before import to database. However i try to do an export data from the database and showed it in table form, I cannot perform edit function before exporting it. Can make a tutorial on how to do this? Thank you very much 🙂

    Reply
  5. hi I used this select statement with your code all seem to work except saving the record though it displays save successfully. I changed all the fields that is needed to be change in example1 and example2 based on this sql but im not sure what im messing here’s he SQL i used inside te table tag

    Id
    Student Name
    Quiz
    Class Activity
    Assignment
    Exam
    Prelim Total Grade

    <input type='text' class='txtedit' value='’ id=’studname_’ >

    <input type='text' class='txtedit' value='’ id=’pquiz_’ >

    <input type='text' class='txtedit' value='’ id=’pclassact_’ >

    <input type='text' class='txtedit' value='’ id=’pass_’ >

    <input type='text' class='txtedit' value='’ id=’pex_’ >

    <input type='text' class='txtedit' value='’ id=’ptg_’ >

    Reply
  6. Great example, been looking for something like this for awhile. It works great, my only issue is when I make a change, spaces appear before and after the change when stored in the database. The spaces even appear when I click into the table and not change anything. What do you think is causing this issue?

    Reply
  7. hye,

    i just add more field to update..but only one field is updated and when i try again it didn’t work like before.What do you think is causing this issue?

    Reply

Leave a Reply to kezaco Cancel reply