I cannot update my data in datatable - cannot reinitialise DataTable

Viewed 59

everyone. I have a table in which I show some data based on two values from datetimepickers. The datetemipickers are for From date and To date. When I first run into the table of course the datetimepickers are empty. For this situation, I have default values and everything is working fine with them. After that I am trying to put some dates in the datetimepickers, click on a button to call ajax function actionTaskReportPerPeriod. The function works and in the console of the browser, I see the data it has returned. But the table is reloaded with the old data from the default datetimepickers values. Here is my TaskReportPerPeriod function:

public function actionTaskReportPerPeriod()
    {
        $aColumns = array(
          'task_id',
          'trans_type',
          'task_description',
          'driver_name',
          'customer_name',
          'delivery_address',
          'delivery_date' ,
          'status'
        
        );

        $date_from = isset($this->data['task_report_start_date'])?$this->data['task_report_start_date']:date('2021-09-01 00:00:00');
        $date_to = isset($this->data['task_report_end_date'])?$this->data['task_report_end_date']:date('Y-m-d H:i:s');
        

        $t=AjaxDataTables::AjaxData($aColumns);     
        if (isset($_GET['debug'])){
            dump($t);
        }
        
        if (is_array($t) && count($t)>=1){
            $sWhere=$t['sWhere'];
            $sOrder=$t['sOrder'];
            $sLimit=$t['sLimit'];
        }   
                
        $and='';        
        $and=" AND delivery_date >= '$date_from' AND delivery_date <= '$date_to' AND customer_id =".Driver::q(Driver::getUserId())."  ";
        
        $stmt="SELECT SQL_CALC_FOUND_ROWS *
        FROM
        {{driver_task_view}}
        WHERE 1     
        $and
        $sWhere
        $sOrder
        $sLimit
        ";
        if (isset($_GET['debug'])){
           dump($stmt);
        }
        
        $_SESSION['kartero_stmt_taskList']=$stmt;
                
        $DbExt=new DbExt; 
        $DbExt->qry("SET SQL_BIG_SELECTS=1");
        
        if ( $res=$DbExt->rst($stmt)){
            
            $iTotalRecords=0;                       
            $stmtc="SELECT FOUND_ROWS() as total_records";
            if ( $resc=$DbExt->rst($stmtc)){                                    
                $iTotalRecords=$resc[0]['total_records'];
            }
            
            $feed_data['sEcho']=intval($_GET['sEcho']);
            $feed_data['iTotalRecords']=$iTotalRecords;
            $feed_data['iTotalDisplayRecords']=$iTotalRecords;                                      
            
            foreach ($res as $val) {
                $date_created=AdminFunctions::prettyDate($val['delivery_date'],true);
                $date_created=Yii::app()->functions->translateDate($date_created);      
                
                $status="<span class=\"tag ".$val['status']." \">".Driver::t($val['status'])."</span>"; 
                
                $action="<a class=\"btn btn-primary task-details\"
                    data-id=\"".$val['task_id']."\" href=\"javascript:;\">".t("Details")."</a>";
                
                if ( $val['status']=="unassigned"){
                    $action="<a class=\"btn btn-default assign-agent\"
                    data-id=\"".$val['task_id']."\" href=\"javascript:;\">".Driver::t("Assigned")."</a>";
                }
                
                $ratings='<div class="raty-stars" data-score="'.$val['ratings'].'"></div>';

                  $feed_data['aaData'][]=array(
                  $val['task_id'],
                  date("Y-m-d",strtotime($val['delivery_date'])),
                  Driver::t($val['trans_type']),
                  $val['task_description'],
                  $val['driver_name'],
                  $val['customer_name'],
                  $val['delivery_address'],
                  $date_created,
                  $ratings,
                  $val['rating_comment'],

                  $val['dropoff_contact_name'], 
                  $val['drop_address'],
                  $val['dropoff_task_lat']."  ". $val['dropoff_task_lng'],
                  $val['Task_insert_root'],
     
                  $val['delivery_charge'],//Driver::t("Delivery fee"), 
                  $val['team_name'],//   Driver::t("City"), 
                  $val['distance_assigned_to_pickup'],//Driver::t("Pickup distance"), 
                  $val['distance_pickup_to_dropoff'],//Driver::t("Dropoff distance"), 
                  $val['arrived_at_pickup'],//Driver::t("Arrived at restaurant"), 
                  $val['delivery_date'],//Driver::t("Delivery_date"), 
            
                  $val['dropoff_before'],//Driver::t("dropoff_before"), 
                  $val['arrived_at_dropoff'],//Driver::t("Arrived at dropoff"), 
                  $val['stoppage_at_pickup'],//Driver::t("Driver at restaurant time"), 
                  $val['delay_pickup'],//Driver::t("Vendor late pickup"), 
                  $val['delay_dropoff'],//Driver::t("Driver late dropoff"),
                  $val['total_w_tax'],//Driver::t("Driver late dropoff"),
                  $val['dropoff_contact_number'],//Driver::t("Driver late dropoff")
                  $val['payment_type'],//Driver::t("Driver late dropoff")

                  $status ,
                  $action


                
                );              
            }
            if (isset($_GET['debug'])){
               dump($feed_data);
            }
            $this->otableOutput($feed_data);    
        }
        
        $this->otableNodata();
    }

By clicking on the following button I am getting the values from the datetimepickers, which the user has chosen. Then I call my function actionTaskReportPerPeriod by callAjax. And after that, I am trying to call initTable so that it changed the datatable values, but I get the following message: following message

        $( document ).on( "click", ".generate-task", function() {   

            var params= "task_report_start_date=" + $(task_report_start_date).val();
            params+= "&task_report_end_date=" + $(task_report_end_date).val();
            
            console.log('test console output'); 
            callAjax("TaskReportPerPeriod", params);
            initTable();
            tableReload();
            });

Here is my code for initTable, I tried to add "destroy": true, in data_table = $('#table_list').dataTable({ then the message is not showing anymore, but at the same time it continue not working as I expect.

    function initTable()
    {           
        debugger;
        var params=$("#frm_table").serialize(); 
        var action= $("#frm_table #action").val();  
        
        params+="&language="+language;
            
        data_table = $('#table_list').dataTable({   
            "iDisplayLength": 20,
            "bProcessing": true,           
            "bServerSide": true,                
            "sAjaxSource": ajax_url+"/"+ action +"/?currentController=admin&"+params,          
            "aaSorting": [[ 0, "DESC" ]],          
            "sPaginationType": "full_numbers",  
            //"bFilter":false,            
            "bLengthChange": false,
            "oLanguage":{            
                "sProcessing": "<p>Processing.. <i class=\"fa fa-spinner fa-spin\"></i></p>"
            },      
            "oLanguage": {
                "sEmptyTable":    js_lang.tablet_1,
                    "sInfo":           js_lang.tablet_2,
                    "sInfoEmpty":      js_lang.tablet_3,
                    "sInfoFiltered":   js_lang.tablet_4,
                    "sInfoPostFix":    "",
                    "sInfoThousands":  ",",
                    "sLengthMenu":     js_lang.tablet_5,
                    "sLoadingRecords": js_lang.tablet_6,
                    "sProcessing":     js_lang.tablet_7,
                    "sSearch":         js_lang.tablet_8,
                    "sZeroRecords":    js_lang.tablet_9,
                    "oPaginate": {
                        "sFirst":    js_lang.tablet_10,
                        "sLast":     js_lang.tablet_11,
                        "sNext":     js_lang.tablet_12,
                        "sPrevious": js_lang.tablet_13
                    },
                    "oAria": {
                        "sSortAscending":  js_lang.tablet_14,
                        "sSortDescending": js_lang.tablet_15
                    }
            },   
            "fnInitComplete": function(oSettings, json) {                         
                    if ( $(".raty-stars").exists() ){
                        initRating(); 
                    }
            },
            "fnDrawCallback": function( oSettings ) {
                dump('fnDrawCallback');            
                setTimeout(function () {
                        dump('init rating');
                        if ( $(".raty-stars").exists() ){
                            dump('run rating');
                            initRating(); 
                        }
                    }, 100);               
            }
        });
    }

Here is the table code:


<div id="layout_1">
<?php 
$this->renderPartial('/tpl/layout1_top',array(   
));
?> 
</div> <!--layout_1-->

<div class="parent-wrapper task-list-area">

 <div class="content_1 white">   
   <?php 
   $this->renderPartial('/tpl/menu',array(   
   ));
   ?>
 </div> <!--content_1-->
 
 <div class="content_main">

   <div class="nav_option">
      <div class="row">
        <div class="col-md-6 border">
         <b><?php echo t("Task report per period")?></b>
        </div> <!--col-->
        <div class="col-md-6 border text-right">
                       
           <a class="orange-button left rounded" href="javascript:tableReload();"><?php echo t("Refresh")?></a>
           
           <a class="green-button left rounded" href="<?php echo Yii::app()->createUrl('/app/export_task')?>">
           <?php echo t("Export")?>
           </a>           
         
        </div> <!--col-->
      </div> <!--row-->
   </div> <!--nav_option-->


   <div class="row top6">
            <div class="col-md-1 ">
                 <h5 class="top2"><?php echo Driver::t("From date ")?></h5> 
            </div>
            <span class="col-md-1 "><?php echo CHtml::textField('task_report_start_date','',array(//delivery before calendar
                'placeholder'=>Driver::t("From date"),
                'required'=>true,
                'class'=>"datetimepicker"
              ))?>
            </span>

            <div class="col-xs-1 ">
            </div>

            <div class="col-xs-1 ">
                 <h5 class="top2"><?php echo Driver::t("To date ")?></h5> 
            </div>
            <div class="col-xs-1 "><?php echo CHtml::textField('task_report_end_date','',array(//delivery before calendar
                'placeholder'=>Driver::t("To date"),
                'required'=>true,
                'class'=>"datetimepicker"
              ))?>
            </div>

            <button type="button" data-id=".generate-task" 
            class="generate-task green-button inline rounded"><?php echo t("Generate Report")?></button>
    </div> <!--row-->
  
   <div class="inner">
   <form id="frm_table" class="frm_table">
   <?php echo CHtml::hiddenField('action','taskReportPerPeriod')?>
   <table id="table_list" class="table table-hover">
   <thead>
    <tr>
      <th width="5%"><?php echo t("Task ID")?></th>     
      <th><?php echo t("Data")?></th> 
      <th><?php echo t("Task Type")?></th>
      <th><?php echo t("Description")?></th>
      <th><?php echo t("Driver Name")?></th>
      <th><?php echo t("Name")?></th>
      <th><?php echo t("Address")?></th>
      <th><?php echo t("Delivery Date")?></th>
      <th width="3%"><?php echo t("Ratings")?></th>
      <th width="2%"><?php echo t("Ratings Comments")?></th>

      <th><?php echo t("Customer Name")?></th> 
      <th><?php echo t("Customer Address")?></th>
      <th><?php echo t("Cust map coord")?></th>
      <th><?php echo t("Task source")?></th>
      
 
      <th><?php echo Driver::t("Delivery fee")?></th> 
      <th><?php echo Driver::t("City")?></th> 
      <th><?php echo Driver::t("Pickup distance")?></th> 
      <th><?php echo Driver::t("Dropoff distance")?></th> 
      <th><?php echo Driver::t("Arrived at restaurant")?></th> 
      <th><?php echo Driver::t("Pickup")?></th> 

      <th><?php echo Driver::t("Dropoff")?></th> 
      <th><?php echo Driver::t("Arrived at dropoff")?></th> 
      <th><?php echo Driver::t("Driver at restaurant time")?></th> 
      <th><?php echo Driver::t("Vendor late pickup")?></th> 
      <th><?php echo Driver::t("Driver late dropoff")?></th> 
      <th><?php echo Driver::t("Total")?></th> 
      <th><?php echo Driver::t("Customer's phone")?></th> 
      <th><?php echo Driver::t("Payment type")?></th> 
      <th><?php echo Driver::t("Status")?></th>      
      <th><?php echo Driver::t("Check")?></th>

    </tr>
    </thead>
    <tbody>     
    </tbody>     
   </table>
   </form>
   </div>
 
 </div> <!--content_2-->

</div> <!--parent-wrapper-->

I will give you some photos from the console of the browser to make the problem a bit more clear.

When I first open the table pictures 1 and 2 are proceed. Then I put some values in the datetimepicker and pictures 3 and 4 are proceed first and after them again 1 and 2. The result in the table for both are the 354 iTotalRecords from picture 2, but I want the second time to retrieve the results from picture 4. 1 2 3 4

0 Answers
Related