A Simple Ajax Driven Editable Table in CodeIgniter


The contenteditable attribute is one of the new most helpful addition in HTML5. Today we are utilising the contenteditable attribute in HTML5 to build a simple ajax driven editable table in CodeIgniter. For sake of simplicity, the table contains just two columns in which one of which is ID and other one is Title of Blog Posts and when you double click Title column it becomes editable and you can save its contents by pressing Enter Key. Although this tutorial is made with a demo CodeIgniter application, you can easily customise it for any PHP projects.

SO LET'S START CODING

The Controller

The complete code in the Table controller is given below.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Table extends CI_Controller {

	Public function __construct() { 
        parent::__construct(); 
         
        $this->load->model('Tablemodel');
         
	} 

	public function index()
	{
        $data['posts'] = $this->Tablemodel->posts();

		$this->load->view('header');
		$this->load->view('tablepage',$data);
		$this->load->view('footer');
	}

	public function savedata()
    {
        If( $_SERVER['REQUEST_METHOD']  != 'POST'  ){
            redirect('table');
        }
        
        $id = $this->input->post('id',true);
        $title = $this->input->post('title',true);
        
        $fields = array(
                    'title' => $title,
                  );
        
        $this->Tablemodel->posts_save($id,$fields);
        
        echo "Successfully saved";
          
    }

}

The savedata() method is triggered by ajax to update the content of the table. For the sake of simplicity, I am not doing any sort of form validations in that method Instead, I do basic checks like whether the requested method is the post or not and some basic XSS cleaning by giving the second parameter of the CodeIgniter input class post as true.

The Model

The complete code for Tablemodel is given below.

<?php

class Tablemodel extends CI_Model 
{
    function __construct() {
        parent::__construct();  // call model constructor
        
    }
    
    function posts()
    {   
       $query = $this
                ->db
                ->limit(10)
                ->get('posts');
        
        if($query->num_rows()>0)
        {
            return $query->result(); 
        }
        else
        {
            return null;
        }
        
    }
   
    function posts_save($id,$fields)
    {
          $this ->db
                ->where('id',$id)
                ->update('posts',$fields);
    }

}

The model is very basic with two functions one for fetching details and one for updating details. No big deal.

View Page

Before we look at the contents of our view page lets take a look at javascript function which is triggered when pressing Enter Key. The saveData() method is responsible for handling Ajax requests.

<script>
function saveData(e,id,title) {
  if(e.keyCode === 13){
    if (confirm('Are you sure you want to save this thing into the database?')) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "<?php echo base_url('table/savedata')?>",
        data: {  '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
                'id': id,
                'title' :title,
              },
        success: function(response){ 
          alert(response);
        }
      });
    }  
 }  
}
</script>

The keycode 13 represent Enter Key and if user press Enter key and true the confirmation alert then the jQuery Ajax function is triggered.

Note: Do not forget to pass CSRF Token along with ajax POST request as above if you turn on CSRF protection in CodeIgniter config file. Cross Site Request Forgery protection is by default turned off in CodeIgniter. If you like to get maximum security in your application you can turn it on config.php file. If you enable CSRF protection don't forget to turn csrf_regenerate to false as it causes problems with back/forward navigation, multiple tabs/windows, asynchronous actions, etc.

For debugging and to see ajax post parameters you can use Firebug in Firefox or Google Chrome DevTools. Firebug is my favourite and easy to use but Google Chrome developer tools also work well. Monitor the Network tab in the console.

Now the complete code for tablepage.php file 

<style>
.inEdit{
      background-color: #ccc;
      border: 1px solid #333 ;
      border-radius: 16px;
}
</style>

<div class="container">
  <a><h3 class="text-center">Ajax Driven Editable Table CodeIgniter - Demo</h3></a>
  <div class="col-md-8 col-md-offset-2">
    <div class="table-responsive">
      <table  class="table table-bordered" width="100%" >
        <thead>
          <tr>
  		      <th>ID</th>
            <th>Title</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          foreach ($posts as $post)   	   
    	     {            
          ?> 
          <tr> 
    	      <td ><?php echo $post->id; ?></td>
            <td title="Double click to Edit and press Enter to Save" ondblclick="this.contentEditable=true; this.className='inEdit';" onblur="this.contentEditable=false; this.className='';" onkeypress="saveData(event,'<?php echo $post->id; ?>',$(this).html() )"><?php echo $post->title; ?></td>
    		  </tr> 
          <?php                          
            }
          ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
    <!-- Refer Above Javascript Code -->
</script>

On double click, the contentEditable property of that cell become true and a new class inEdit is assigned to it. On blur, the contentEditable property and inEdit class are removed. Every time you type something in editable cell saveData() method is called. I used this keyword to represent the current cell in the table.

Now let's see the output image.

Ajax Driven Editable Table CodeIgniter - Demo

If anybody has any suggestions or doubts or need any help comment below and I try will response to every one of you as early as possible.


Web development
11th Jun 2017 10:03:01 PM
PHP CodeIgniter Javascript jQuery Ajax Bootstrap HTML & CSS
12133

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.