简体   繁体   中英

Ajax datatable not properly working in Laravel

I am a stuck with a problem.

I am having an ajax Datatable where I need to load the data via ajax. When I implemented the code Datatable pagination and sorting is not working. No error is displayed in the console. Don't know what to do. here is my code...........

Controller Function

public function ajaxdata(Request $request)
    {

        $merchants  =   \DB::table('merchantsummary')->lists('id');
        $queryBuilder   =   OrderQueueModel::take($request->input('length'))
                            ->skip($request->input('start'))->select('order_queue.qid','order_queue.qorder_no','order_queue.created_at','customer.first_name','customer.last_name','merchant_queue_order.created_at as merchant_order_time')
                                        ->join('customer','customer.id','=','order_queue.customerid')
                                        ->join('merchant_queue_order','order_queue.qid','=','merchant_queue_order.order_queue_id')
                                        ->groupBy('merchant_queue_order.order_queue_id');




        $orders = $queryBuilder->get();

        $data = array();
        $i=1;
        foreach($orders as $order):
        $merchant           =   MerchantOrderQueueModel::select('merchantsummary.merchant_name','merchant_queue_order.order_queue_id')
                                                        ->join('merchantsummary','merchantsummary.id','=','merchant_queue_order.merchant_id')
                                                        ->WHERE('merchant_queue_order.order_queue_id',$order->qid)
                                                        ->get();
        $merchList = '';
        foreach($merchant as $mer):

            if($merchList!=''){
                $merchList .= ', ';
            }
            $merchList .= $mer->merchant_name;
        endforeach;
            $data[] = [ $i,
                        $order->qorder_no,
                        ucfirst($order->first_name).ucfirst($order->last_name),
                        date('d-m-Y H:i A', strtotime($order->created_at)),
                        date('d-m-Y H:i A', strtotime($order->merchant_order_time)),
                        $this->dateDifference($order->merchant_order_time,$order->created_at),
                        $merchList,
                        '<a href="'.url('admin/orderdetails',array('id' => $order->qid)).'" ><i class="fa fa-search"></i> View</a>',
                        ];
            $i++;
        endforeach;

        $totaldata = OrderQueueModel::count();
        $totalfiltered = $orders->count();

        $json_data = array(
                "draw"            => intval( $_REQUEST['draw'] ),
                "recordsTotal"    => intval( $totaldata ),
                "recordsFiltered" => intval( $totalfiltered ),
                "data"            => $data
        );

        echo json_encode($json_data);
    }

TableAjax.js

var orderRecords = function () {

        var grid = new Datatable();

        grid.init({
            src: $("#order_ajax"),
            onSuccess: function (grid) {
                // execute some code after table records loaded
            },
            onError: function (grid) {
                // execute some code on network or other general error  
            },
            onDataLoad: function(grid) {
                // execute some code on ajax data load

            },
            loadingMessage: 'Loading...',
            dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options 

                // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
                // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js). 
                // So when dropdowns used the scrollable div should be removed. 
                //"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>",

                "bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.

                "lengthMenu": [
                    [5,10, 20, 50, 100],
                    [5,10, 20, 50, 100] // change per page values here
                ],

                "pageLength": 5, // default record count per page
                "serverSide": true,
                 "columnDefs":[
                    { // set default column settings 
                    'orderable': true, 'targets': [0] },
                    { "searchable": true, "targets": [0] },
                ],
                "ajax": {
                    "url": "order/data", // ajax source
                },
                "order": [
                    [1, "asc"]
                ]// set first column as a default sort by asc
            }
        });

        // handle group actionsubmit button click
        grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
            e.preventDefault();
            var action = $(".table-group-action-input", grid.getTableWrapper());
            if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
                grid.setAjaxParam("customActionType", "group_action");
                grid.setAjaxParam("customActionName", action.val());
                grid.setAjaxParam("id", grid.getSelectedRows());
                grid.getDataTable().ajax.reload();
                grid.clearAjaxParams();
            } else if (action.val() == "") {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'Please select an action',
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            } else if (grid.getSelectedRowsCount() === 0) {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'No record selected',
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            }
        });
    }

Need Help !! Waiting for the response..

The easiest way to apply server side data-table is:

Jquery:

$(document).ready(function() {
    $('#data_table').dataTable({
        "sServerMethod": "POST", 
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "get_data.php"
    });
});

Php: get_data.php

$start  = $_REQUEST['iDisplayStart'];  // to handle pagination
$length = $_REQUEST['iDisplayLength']; // to handle pagination
$sSearch = $_REQUEST['sSearch'];       // for searching

$col = $_REQUEST['iSortCol_0'];

$arr = array(0 => 'id', 1 => 'first_name', 2 => 'last_name', 3 => 'email');

$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];

$qry = "select id, first_name, last_name, email, position, office from datatables_demo where (first_name LIKE '%".$sSearch."%' or last_name LIKE '%".$sSearch."%' or email LIKE '%".$sSearch."%') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
    $data[] = $row;
}

$qry = "select count(id) as count from datatables_demo";
$res = mysql_query($qry);

while($row =  mysql_fetch_assoc($res))
{
    $iTotal = $row['count'];
}

$rec = array(
    'iTotalRecords' => $iTotal,
    'iTotalDisplayRecords' => $iTotal,
    'aaData' => array()
);

$k=0;
if (isset($data) && is_array($data)) {

    foreach ($data as $item) {
        $rec['aaData'][$k] = array(
            0 => $item['id'],
            1 => '<span id="'.$item['id'].'" name="first_name" class="editable">'.$item['first_name'].'</span>',
            2 => '<span id="'.$item['id'].'" name="last_name" class="editable">'.$item['last_name'].'</span>',
            3 => '<span id="'.$item['id'].'" name="email" class="editable">'.$item['email'].'</span>',
            4 => '<span id="'.$item['id'].'" name="position" class="editable">'.$item['position'].'</span>',
            5 => '<span id="'.$item['id'].'" name="office" class="editable">'.$item['office'].'</span>'
        );
        $k++;
    }
}

echo json_encode($rec);

Its a little bit tough to understand the code on first time, but it will render full functional server side data-table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM