Make Live Editable Table with jQuery AJAX

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 you have doesn’t need to send the user to edit form page.
It is user-friendly and timesaving.
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 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.
Completed Code
<?php

include "config.php";

$field = $_POST['field'];
$value = $_POST['value'];
$editid = $_POST['id'];

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

echo 1;

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){
    console.log('Save successfully'); 
   }
  });
 
 });

});

4. Demo 1

Click on the Table cell to edit.

5. Show Input Element

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

HTML

In the table cell with <div> container also creating input element which is shown only when the user clicks on the <div> container. This does with jQuery.
Both of them contains 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){
    console.log('Save successfully'); 
   }
  });
 
 });

});

6. Demo 2

Click on the cell and input value in the text box.

7. Conclusion

Live data editing is a quick and easy way to allow users to modify the contents.
I showed you two ways for implementing this you can use any one of them in your project.
Within the demonstration, I used 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.

Komentar

Postingan populer dari blog ini

Login, Session, dan Logout

Cara Membuat File Setup / Installer Aplikasi Sendiri dengan Inno Setup Compiler