Tag Archive อาเจ็ก

Byphunsanit

slick: carousel / slideshow จาก ajax

ตัวอย่างการแก้ไข carousel หรือ slideshow โดย update slide จาก ajax

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>kenwheeler.slick: ajax update</title>
    <link href="../vendor/components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <link href="../vendor/kenwheeler/slick/slick/slick.css" rel="stylesheet" type="text/css" />
    <link href="../vendor/kenwheeler/slick/slick/slick-theme.css" rel="stylesheet" type="text/css" />
    <link href="theme.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="slideshowA"></div><br>
    <select id="order_by">
    <option value="asc">น้อยไปมาก</option>
    <option value="desc">มากไปน้อย</option>
    <option value="random">สุ่ม</option>
    </select>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script src="../vendor/kenwheeler/slick/slick/slick.min.js"></script>
    <script>
        $(function() {

            var order_by = $('#order_by');
            var slideshowA = $('#slideshowA');

            function getSliderSettings() {
                return {
                    "autoplay": false,
                    "autoplaySpeed": 3000,
                    "centerMode": true,
                    "infinite": false,
                    "slidesToScroll": 4,
                    "slidesToShow": 4,
                    "speed": 300,
                    "variableWidth": true,
                    "zIndex": 2
                }
            }

            function getSlideShow() {

                $.ajax({
                    "data": {
                        "order_by": order_by.val(),
                    },
                    "success": function(data, textStatus, jqXHR) {

                        /* add items */
                        $.each(data.datas, function(index, value) {
                            slideshowA.append('<div><b>' + index + '</b><img alt="' + index + '" src="' + value + '"><p>แสดง ' + index + ' จาก http://www.avatarsdb.com</p></div>');
                        });

                        slideshowA.slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
                        $('.my-slide').remove(); /* Remove current slides elements, in case that you want to show new slides. */
                        slideshowA.slick(getSliderSettings()); /* Initialize the slick again */

                        alert('ทดลองดูครับ');

                    },
                    "url": "ajax.php",
                });

            }

            order_by.change(function() {
                getSlideShow();
            });

            getSlideShow();
            slideshowA.slick(getSliderSettings());
        });
    </script>
</body>

</html>

ไฟล์ที่ส่งข้อมูลกลับมาให้

<?php
$datas = [];

if (isset($_GET['order_by'])) {
    $order_by = $_GET['order_by'];
} else {
    $order_by = 'asc';
}

$datas['Acrobat'] = 'http://www.avatarsdb.com/avatars/acrobat.gif';
$datas['Cat Rain'] = 'http://www.avatarsdb.com/avatars/cat_rain.gif';
$datas['Dota Windranger'] = 'http://www.avatarsdb.com/avatars/dota_windranger.jpg';
$datas['Fighting Funny'] = 'http://www.avatarsdb.com/avatars/fighting_funny.gif';
$datas['Fire 01'] = 'http://www.avatarsdb.com/avatars/fire_01.gif';
$datas['German Shepherd Puppy'] = 'http://www.avatarsdb.com/avatars/german_shepherd_puppy.jpg';
$datas['Girl With Cigarette'] = 'http://www.avatarsdb.com/avatars/girl_with_cigarette.jpg';
$datas['Hidden Cat'] = 'http://www.avatarsdb.com/avatars/hidden_cat.jpg';
$datas['Im Fabulous'] = 'http://www.avatarsdb.com/avatars/im_fabulous.jpg';
$datas['One Direction'] = 'http://www.avatarsdb.com/avatars/One_Direction.jpg';
$datas['Panda Kiss'] = 'http://www.avatarsdb.com/avatars/panda_kiss.gif';
$datas['PC User'] = 'http://www.avatarsdb.com/avatars/pc_user.gif';
$datas['Riri Queen'] = 'http://www.avatarsdb.com/avatars/riri_queen.gif';
$datas['Tennessee'] = 'http://www.avatarsdb.com/avatars/tennessee.jpg';
$datas['Tuxedo M'] = 'http://www.avatarsdb.com/avatars/Tuxedo_m.jpg';
$datas['Tuxedo Mask'] = 'http://www.avatarsdb.com/avatars/tuxedo_mask.jpg';
$datas['Ugly Face'] = 'http://www.avatarsdb.com/avatars/ugly_face.gif';
$datas['Waifu'] = 'http://www.avatarsdb.com/avatars/waifu.jpg';
$datas['Wolf In The Snow'] = 'http://www.avatarsdb.com/avatars/wolf_in_the_snow.jpg';
$datas['Xerxes Break Kevin'] = 'http://www.avatarsdb.com/avatars/xerxes_break_kevin.jpg';

switch ($order_by) {
    case 'desc':{krsort($datas);}
        break;

    case 'random':{
            $keys = array_keys($datas);
            shuffle($keys);
            $random = [];
            foreach ($keys as $key) {
                $random[$key] = $datas[$key];
            }
            $datas = $random;
        }break;

    case 'asc':
    default:
        {ksort($datas);}
        break;
}

header('Content-type: application/json; charset=utf-8');
echo json_encode([
    'datas' => $datas,
    'order_by' => $order_by,
]);

code บางส่วนจะอยู่ในบทความ slick: สร้าง carousel / slideshow

Credit: Reinitialize Slick js after successful ajax call

Byphunsanit

DataTable: ดัดแปลง / คัดลอก ข้อมูล

แนวคิดคือ คัดลอกข้อมูลที่เลือกเอาไว้จาก DataTables ตัวหนึ่งไปยังอีกตัวหนึง

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="author" content="Pitt Phunsanit">
    <title>DataTables: Transfer Data To Another Table</title>
    <link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="../vendor/twbs/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css">
    <link href="../vendor/datatables/datatables/media/css/dataTables.bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="../assets/fronteed/icheck/skins/minimal/red.css" rel="stylesheet" type="text/css">
</head>

<body>
    <table class="table table-bordered table-hover table-striped" id="filtersTableA" width="100%"></table>
    <button class="btn btn-success" id="copyBtn" type="button">Copy Data To Table</button>
    <table class="table table-bordered table-hover table-striped" id="tableA" width="100%"></table>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script src="../vendor/datatables/datatables/media/js/jquery.dataTables.min.js"></script>
    <script src="../vendor/datatables/datatables/media/js/dataTables.bootstrap.min.js"></script>
    <script src="../assets/fronteed/icheck/icheck.min.js"></script>

    <script src="DataTables.js"></script>

    <script src="data.json.transferDataToAnotherTable.js"></script>
</body>

</html>

ส่วนที่เขียนเป็นฟังก์ชั่นกลางไว้ให้ไฟล์อื่นเรียกใช้

function iCheckBulk(dataTableArea, dataTableObject) {
    dataTableArea.on('ifChanged', '.checkAll', function(event) {

        var datas = dataTableObject.data();
        var inputs = $('input:checkbox, input:radio', dataTableArea);

        if (event.target.checked) {
            var enable = '1';
            var state = 'check';
        } else {
            var enable = '0';
            var state = 'uncheck';
        }

        $.each(datas, function(index, value) {
            value.enable = enable;

            dataTableObject.row(index).data(value);
        });

        iCheckInit($('input:checkbox, input:radio', dataTableArea));
    });

}

/* change filtersTable data value on input name enables is change */
function iCheckChange(filtersTableArea, filtersTableObject, dataTableObject) {
    $('tbody', filtersTableArea).on('ifChanged', 'input[name="enables[]"]', function(event) {

        event.stopPropagation();

        var row = $(this).closest('tr');

        var data = filtersTableObject.row(row).data();

        if ($(this).is(':checked')) {
            $(this).attr('checked', 1);
            data.enable = true;
        } else {
            $(this).attr('checked', 0);
            data.enable = false;
        }
        filtersTableObject.row(row).data(data);

        iCheckInit(row);
    });
}

function iCheckCopy(dataTableObject, filtersTableObject, pkField) {
    $('#copyBtn').click(function() {

        /* loop current data (pkField) in current dataTableObject */
        var datas = dataTableObject.data();
        var hasKeys = new Array();
        $.each(datas, function(index, value) {
            hasKeys.push(value[pkField]);
        });

        var datasChoose = filtersTableObject.data();

        $.each(datasChoose, function(index, value) {
            /* add row to filtersTableObject if input name enables[] is checked */
            if (value.enable == true && hasKeys.indexOf(value[pkField]) == -1) {
                dataTableObject
                    .row.add(value)
                    .draw()
                    .node();
            }
        });

    });

}

function iCheckInit(selector) {
    selector.iCheck({
        checkboxClass: 'icheckbox_minimal-red',
        radioClass: 'iradio_minimal-red',
    });
}

ไฟล์ที่ทำหน้าที่ควบคุมการคัดลอกข้อมูล

$(function() {

    dataTableA = $('#dataTableA');
    filtersTableA = $('#filtersTableA');
    tableA = $('#tableA');

    filtersTable = filtersTableA
        .DataTable({
            "ajax": {
                "data": function(parameters) {},
                "method": "POST",
                "url": "data.json.php",
            },
            "columns": [{
                    "orderable": false,
                    "render": function(data, type, row, meta) {
                        return parseInt(meta.row) + parseInt(meta.settings._iDisplayStart) + 1;
                    },
                    "title": 'No.',
                    "width": "10px",
                },
                {
                    "orderable": false,
                    "render": function(data, type, row, meta) {
                        if (row.enable == '1') {
                            var checked = ' checked';
                        } else {
                            var checked = '';
                        }

                        return '<input' + checked + ' name="enables[]" type="checkbox" value="' + row.DISTRICT_CODE + '">';
                    },
                    "title": '<input class="checkAll" type="checkbox">',
                    "width": "10px",
                },
                {
                    "orderable": false,
                    "render": function(data, type, row, meta) {
                        if (row.enable == '1') {
                            return '<span class="glyphicon glyphicon-ok"></span>';
                        } else {
                            return '<span class="glyphicon glyphicon-remove"></span>';
                        }
                    },
                    "title": "Enable",
                    "width": "10px",
                }, {
                    "data": "DISTRICT_CODE",
                    "title": "District Code",
                    "width": "90px",
                }, {
                    "data": "DISTRICT_NAME",
                    "title": "District Name",
                }, {
                    "data": "PROVINCE_NAME",
                    "title": "Province Name",
                }
            ],
            "processing": true,
            "serverSide": true,
            "stateSave": true
        })
        .on('draw', function(event, settings, json, xhr) {
            /* add style to checkbox, radio */
            iCheckInit($('input:checkbox, input:radio', settings.nTable));
        });

    iCheckBulk(filtersTableA, filtersTable);

    dataTable = tableA
        .DataTable({
            "columns": [{
                    "orderable": false,
                    "render": function(data, type, row, meta) {
                        return parseInt(meta.row) + parseInt(meta.settings._iDisplayStart) + 1;
                    },
                    "title": 'No.',
                    "width": "10px",
                },
                {
                    "orderable": false,
                    "render": function(data, type, row, meta) {
                        if (row.enable == 1) {
                            var checked = ' checked';
                        } else {
                            var checked = '';
                        }

                        return '<input' + checked + ' name="enables[]" type="checkbox" value="' + row.DISTRICT_CODE + '">';
                    },
                    "title": '<input class="checkAll" type="checkbox">',
                    "width": "10px",
                },
                {
                    "orderable": false,
                    "render": function(data, type, row, meta) {
                        if (row.enable) {
                            return '<span class="glyphicon glyphicon-ok"></span>';
                        } else {
                            return '<span class="glyphicon glyphicon-remove"></span>';
                        }
                    },
                    "title": "Enable",
                    "width": "10px",
                }, {
                    "data": "DISTRICT_CODE",
                    "title": "District Code",
                    "width": "90px",
                }, {
                    "data": "DISTRICT_NAME",
                    "title": "District Name",
                }, {
                    "data": "PROVINCE_NAME",
                    "title": "Province Name",
                }
            ]
        })
        .on('draw', function(event, settings, json, xhr) {
            /* add style to checkbox, radio */
            iCheckInit($('input:checkbox, input:radio', settings.nTable));
        });

    iCheckBulk(tableA, dataTable);

    iCheckChange(filtersTableA, filtersTable, dataTable);

    iCheckCopy(dataTable, filtersTable, 'DISTRICT_CODE');

});

อธิบาย

  • มี 2 ตารางคือ id=”filtersTableA” เป็นต้นฉบับ และ id=”tableA” เป็นตารางที่จะรับค่าที่จะคัดลอก
  • เพราะว่าอาจจะแบ่งข้อมูลไว้หลายหน้าและ DataTable จะ render ที่ละหน้าเท่านั้น ถ้า user เลือกรายการโดยใช้ input enables[] แล้วเปลี่ยนไปหน้าอื่น input นั้นจะหายไป ทำให้ต้องใช้วิธี update กลับไปที่ Data ของตัว DataTable filtersTableA โดยเปลี่ยนค่าใน object data เช่น data.enable = true; หรือ data.enable = false;
  • เมือคลิก ปุ่ม id=”copyBtn” ให้คัดลอกข้อมูล เพื่อป้องกันการเก็บข้อมูลซ้ำจึงต้อง ดึงรายการที่เก็บข้อมูลเอาไว้แล้ว มาเทียบว่าที่จะเข้ามาใหม่มีรึยังโดยใช้ primary key คือ DISTRICT_CODE

อ่านเพิ่มเติม