Amazon Best Products with minimum price

Friday 31 March 2017

How to Add datepicker in dynamically created row in HTML ???

Datepickers JQuery Plugin allow user to enter dates Easily. Recently, I was working on one of my Project and I got stuck. Want to know what the problem was?

Here it is .. I created the dynamic row in HTML form with Add button and Delete button, but when I added a new row by clicking the add button, it lead in creation of a new row but it wasn't showing the date by using datepicker.

I searched on google but didn't get the answer.. finally by continuous practise and detailed analysis I found the answer and now it's working in my project, so I wanted to share my code with you all. In case, you guys also have faced the same problem, then let's get started...

1) So let's start with HTML <head> tag where we use all CDN of JQuery Library which are used for  Datepicker

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Datepicker for Dynamic added row</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

     
   </head><body></body></html>

In the above code, we load the CDN of Bootstrap and Jquery in the head tag of html page.

2) After adding the CDN of Jquery let's add the table tag in <body> tag of html file.

<!doctype html>
<html lang = "en">
<head></head><body><div style="overflow: scroll;">
<form>
<table class="table" id="dataTable">
<thead>
<tr>
<th>Select</th>
<!--<th>Date</th>-->

<th>Types of Work</th>
<th>Date Assigned</th>
<th>Date Due</th>
<th>Priority</th>
<th>Frequency</th>
<th>Company</th>
<th>Description of Process</th>
<th>Second in Charge</th>
<th>Assigned By</th>
<th>Comments</th>
<th>Question</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="chk"/></td>
<!-- <td><input type="text" name="date[]" value="" /></td>-->
<td><input type="text" name="work[]" value="" class="task" />
<span class="text-danger"><?php echo form_error('work[]');?></span>
  </td>
<td><input type="text" name="assigned_date[]" value="" id="assigned_date" class="assigned_date" />
<span class="text-danger"><?php echo form_error('assigned_date[]');?></span>
</td>
  <td><input type="text" name="last_date[]" value="" id="last_date" class="last_date" />
   <span class="text-danger"><?php echo form_error('last_date[]');?></span>
  </td>
  <td><input type="text" name="priority[]" value="" />
   <span class="text-danger"><?php echo form_error('priority[]');?></span>
  </td>
  <td><input type="text" name="frequency[]" value="" />
   <span class="text-danger"><?php echo form_error('frequency[]');?></span>
  </td>
  <td><input type="text" name="company[]" value="" />
   <span class="text-danger"><?php echo form_error('company[]');?></span>
  </td>
  <td><input type="text" name="description[]" value="" />
   <span class="text-danger"><?php echo form_error('description[]');?></span>
  </td>
  <td><input type="text" name="s_incharge[]" value="" />
   <span class="text-danger"><?php echo form_error('s_incharge[]');?></span>
  </td>
  <td><input type="text" name="assigned_by[]" value="" />
   <span class="text-danger"><?php echo form_error('assigned_by[]');?></span>
  </td>
  <td><input type="text" name="comments[]" value="" />
  </td>
  <td><input type="text" name="question[]" value="" />
  </td>
</tr>

</tbody>
</table>
<input class="btn btn-primary" type="button" value="Add Row" onclick="addRow('dataTable')" id="add_button" />
<input class="btn btn-primary" type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<input class="btn btn-primary" type="submit" name="submit" value="submit">
</form>

</div></body>

Here in the above code, we created the form in Table because we will create one Add button and one Delete button for creating new row of form and deleting the existing form.

Pass the each text box ID for the ajax call in script. On the Add button and Delete button we provide the onclick function. Onclick is a function which occurs when any one clicks that respective button then it calls the specific function.

3) Now we are done with our HTML coding. Thereby let's get started with jquery.

Note: Simply I write JQuery script just before </body> closing tag, Because it calls after loading the page and this way the page speed becomes better.

Here, is the Jquery code:

 function addRow(tableID) {
      $(".last_date").datepicker("destroy");
      $(".assigned_date").datepicker("destroy");
      var table = document.getElementById(tableID);

      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);

      var colCount = table.rows[1].cells.length;

      for(var i=0; i<colCount; i++) {

        var newcell = row.insertCell(i);

        newcell.innerHTML = table.rows[1].cells[i].innerHTML;
        //alert(newcell.childNodes);
        switch(newcell.childNodes[0].type) {
          case "text":
              newcell.childNodes[0].value = "";
              break;
          case "checkbox":
              newcell.childNodes[0].checked = false;
              break;
          case "select-one":
              newcell.childNodes[0].selectedIndex = 0;
              break;
              
        }
      }

     var dateAssignedId = Math.round(new Date().getTime() + (Math.random() * 100));
      var dateDueId = Math.round(new Date().getTime() + (Math.random() * 100));
      $(row).find('.assigned_date')[0].id = dateAssignedId; 
      $(row).find('.last_date')[0].id = dateDueId;
      
      $(".assigned_date").datepicker({dateFormat: "yy-mm-dd"});
      $(".last_date").datepicker({dateFormat: "yy-mm-dd"});
    }

    function deleteRow(tableID) {
      try {
      var table = document.getElementById(tableID);
      var rowCount = table.rows.length;

      for(var i=0; i<rowCount; i++) {
        var row = table.rows[i];
        var chkbox = row.cells[0].childNodes[0];
        if(null != chkbox && true == chkbox.checked) {
          if(rowCount <= 2) {
            alert("Cannot delete all the rows.");
            break;
          }
          table.deleteRow(i);
          rowCount--;
          i--;
        }


      }
      }catch(e) {
        alert(e);
      }
    }
 $(function(){
      $(".assigned_date").datepicker({dateFormat: "yy-mm-dd"});
      $(".last_date").datepicker({dateFormat: "yy-mm-dd"});
  });



In the, JQuery Code we made two functions: One is Add row function and another one is Delete row function and they are called by Add button and Delete button respectively in html form tag by onclick function.

If you guys have any further questions regarding this, feel free to write in the comments down below..

Stay tuned for more coding!!

Thank you!!!!






Thursday 30 March 2017

How to Track any changes made on Database Table???

If you want to track any changes made on your database table, So here is the best solution to track changes made on the database table.

Trigger is a sql code which runs just before or just after an INSERT, UPDATE or DELETE events occur on a particular database table, Triggers have been supported in MYSQL since version 5.0.2

Create your Table in Database:

CREATE TABLE `task` (
  `ID` int(11) NOT NULL,
  `user_name` varchar(25) NOT NULL,
  `date` date NOT NULL,
  `t_name` varchar(25) NOT NULL,
  `partner` varchar(11) NOT NULL,
  `director` varchar(25) NOT NULL,  `duration` float NOT NULL,`task` varchar(255) NOT NULL,`status` varchar(25) NOT NULL,                                            
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `task`
  ADD PRIMARY KEY (`ID`);

ALTER TABLE `task`
  MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;

In the above code, we have created the task table which has the user_name, date, t_name, partner and director column. If any event occur in the above table then, it will fire the trigger and store the record in the table mentioned in trigger query.

Create another table, where you want to track the changes made on the table:

CREATE TABLE `task_log` (
  `ID` int(11) NOT NULL,
  `user_name` varchar(25) NOT NULL,
  `log_action` varchar(25) NOT NULL,
  `log_timestamp` date NOT NULL,                                             
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


The above table, is used for storing the data when any event occur in the task table.
User_name stores the name of the user, Log_action stores those events which occur on the table (insert, update, and delete) and lastly log_timestamp stores the data and time when the specified event occur on the task table.

Fire a Trigger Query in your PhpMyadmin SQL Tab:

CREATE TRIGGER after_update 
                 AFTER UPDATE ON task
                 FOR EACH ROW 

                 INSERT INTO task_log
                 SET log_action = "update",
                 user_name      = NEW.user_name,
                 log_timestamp  = NOW()


If you want to display all the columns then create a new column in task_log and also add row in the trigger Query.

If you have any issues, then feel free to write in the comments down below... will surely get back to you.

Stay tuned for more coding!!

Thank you....

















How to integrate Datatables plugin with CodeIgniter Tutorial??

Datatables is a power plugin of jquery that allows you to display data in tabular format with Searching tab, showing numbers (Example : 10, 20, 50, 100 etc) and Asynchronous pagination.

In this tutorial, I am going to show you how to integrate datatables in codeigniter frame work.

1) Installation or Setup:

You can download datatables file from here: https://datatables.net/  or you can use CDN file of Datatables.

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script> 

 Now, we are going to create Codeigniter file.

application/controller/task.php
application/model/task_model.php
application/view/task/index.php

2) Setting up Datatables in View:

Creating New file index.php in application/view/task

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Book Display</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script> 
    </head>
    <body>
    <h1>Task List</h1>
    </body>
</html>

In the above code, we have loaded the CDN of Jquery and datatables.

This is the simple HTML format page now include the Table in the body tag.

<table id="task-table">
<thead>
<tr><td>Name</td><td>Date</td><td>Work</td><td>Partner</td><td>Director</td><td>Time</td><td>Task</td><td>Status</td></tr>
</thead>
<tbody>
</tbody>
</table>

Above we have created simple table with the heading name : Name, Date, Work, Partner, Director, Time, Task and Status.

Now the next step, is call the Datatables by jquery.

<script type="text/javascript">
$(document).ready(function() {
    $('#task-table').DataTable();
});
</script>

Note: You can call jquery anywhere in body tag, but my recommendation is please use it last before the </body> tag.

It's time to build Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function __construct()
 {
  parent::__construct();
  //Loading the model
  $this->load->model('task_model');
 }
class task extends CI_Controller
{
  
 public function index(){
  $this->load->view("task/index.php", array());
 }
public function task_page()
     {

          // Datatables Variables
          $draw = intval($this->input->get("draw"));
          $start = intval($this->input->get("start"));
          $length = intval($this->input->get("length"));


          $books = $this->task_model->get_task();

          $data = array();

          foreach($books->result() as $r) {

               $data[] = array(
                    '<a href="edit_hodm/'.$r->id.'" >'. $r->user_name .'</a>',
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );
          }

          $output = array(
               "draw" => $draw,
                 "recordsTotal" => $books->num_rows(),
                 "recordsFiltered" => $books->num_rows(),
                 "data" => $data
            );
          echo json_encode($output);
          exit();
     }} ?>

The above controller is used to call all syntax of data tables and pass it to View through the controller.

Then, Create a table in database.

CREATE TABLE `task` (
  `ID` int(11) NOT NULL,
  `user_name` varchar(25) NOT NULL,
  `date` date NOT NULL,
  `t_name` varchar(25) NOT NULL,
  `partner` varchar(11) NOT NULL,
  `director` varchar(25) NOT NULL,  `duration` float NOT NULL,`task` varchar(255) NOT NULL,`status` varchar(25) NOT NULL,                                            
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `task`
  ADD PRIMARY KEY (`ID`);

ALTER TABLE `task`
  MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;

Above we have created the task table with the following column name: User_name, date, t_name, partner, director, duration, status.

Once, we insert data into database then create task_model.php in model.

<?php

class task_model extends CI_Model
{

     public function get_task()
     {
          return $this->db->get("task");
     }

}

?>

get("task") is used to get all record from database and return to the controller.

Here is the complete code of application/view/task/index.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Book Display</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script> 
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
    <div class="row">
    <div class="col-md-12">

    <h1>Task List</h1>

     <table id="task-table" class="table table-bordered table-striped table-hover">
      <thead>
      <tr class="">
       <th>Name</th>
       <th>Date</th>
       <th>Work</th>
       <th>Partner</th>
       <th>Director</th>
       <th>Time</th>
       <th>Task</th>
       <th>Status</th>
     </tr>
      </thead>
      <tbody>
      </tbody>
      </table>

    </div>
    </div>
    </div>
 <script type="text/javascript">
$(document).ready(function() {
    $('#task-table').DataTable({
        "ajax": {
            url : "<?php echo site_url("task/task_page") ?>",
            type : 'GET'
        },
    });
});
</script>
    </body>
</html>


That's it from my side..

If you have any questions, then write in the comments down below OR send me your questions and suggestions to my Email id: aziz.10786@gmail.com.

Thank you!!