Make Live Editable Table with jQuery AJAX

Live editable table is good for update content quickly while viewing it.

This can be used to update full records details or some of them and don’t need to send the user to edit form page.

It is user-friendly and time-saving.

To implementing this I am using jQuery AJAX.

In this tutorial, I show you two ways to make your table columns editable –

  1. Using contentEditable attribute
  2. Showing the input element when the user clicks on the cell.

Make Live Editable Table with jQuery AJAX


Contents

  1. Table structure
  2. Configuration
  3. With ContentEditable
  4. Demo 1
  5. Show Input Element
  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 
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for the database connection.

Completed Code

<?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. With ContentEditable

The contenteditable attribute enables the container to take input values.

HTML –

Displaying user list on the <table>. Creating a <div contenteditable='true'> inside cell which stores the values.

Completed Code

<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.

Completed Code

<?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 –

Saving content when the focus out from <div class='edit'>. In AJAX request passing field name, value, and id.

Completed Code

$(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. Show Input Element

In the second method, instead of making the container editable using input elements that show when the user clicks on the cell.

HTML –

In the table cell with <div> container also create an input element which is shown only when the user clicks on the <div> container using jQuery.

Both of them contain the same values.

Completed Code

<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.

Completed Code

.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.

Completed Code

$(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

Live data editing is a quick and easy way to allow users to modify the content.

I showed you two ways for implementing this you can use any one of them in your project.

Within the demonstration, I used the TextBox element in the second example you also use any other elements like – radio button, checkboxes, etc. according to your requirement.

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.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

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 Comment