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.