Mini Shell

Direktori : /var/www/vhosts/ccp.ac.th/backup_full/httpdocs/fertilizer/
Upload File :
Current File : /var/www/vhosts/ccp.ac.th/backup_full/httpdocs/fertilizer/formula.php

<?php 
// ==========================================
// 1. ส่วนประมวลผลข้อมูลเบื้องหลัง (PHP Backend)
// ==========================================
include 'db/database.php';

if (isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8');
    $action = $_POST['action'];

    // -----------------------------------------
    // ฟังก์ชัน: ดึงข้อมูลสูตรปุ๋ย เพื่อนำไปแสดงใน Modal แก้ไข
    // -----------------------------------------
    if ($action == 'get_formula') {
        $id = mysqli_real_escape_string($link, $_POST['id']);
        
        $formula = mysqli_fetch_assoc(mysqli_query($link, "SELECT * FROM formula WHERE formulaID = '$id'"));
        
        $mothers = [];
        $res_m = mysqli_query($link, "SELECT mother_fertilizer_name_id, mother_quantity FROM mother_fertilizer WHERE formulaID = '$id'");
        if($res_m) { while($r = mysqli_fetch_assoc($res_m)) { $mothers[] = $r; } }
        
        $additives = [];
        $res_a = mysqli_query($link, "SELECT additives_fertilizer_name_id, additives_quantity FROM additives_fertilizer WHERE formulaID = '$id'");
        if($res_a) { while($r = mysqli_fetch_assoc($res_a)) { $additives[] = $r; } }

        echo json_encode([
            'status' => 'success',
            'formula' => $formula,
            'mothers' => $mothers,
            'additives' => $additives
        ]);
        exit();
    }

    // -----------------------------------------
    // ฟังก์ชัน: บันทึกข้อมูลสูตรปุ๋ย
    // -----------------------------------------
    if ($action == 'save_formula') {
        $formulaID = $_POST['formulaID'];
        $name_formula = mysqli_real_escape_string($link, $_POST['name_formula']);
        
        // รับค่า Array ของแม่ปุ๋ยและสารเติมแต่ง
        $m_ids = isset($_POST['mother_name_id']) ? $_POST['mother_name_id'] : [];
        $m_qtys = isset($_POST['mother_qty']) ? $_POST['mother_qty'] : [];
        $a_ids = isset($_POST['additive_name_id']) ? $_POST['additive_name_id'] : [];
        $a_qtys = isset($_POST['additive_qty']) ? $_POST['additive_qty'] : [];

        // ❗ เช็คเงื่อนไข: ผลรวมต้อง "เท่ากับ 100 พอดี" เท่านั้น
        $total_sum = array_sum($m_qtys) + array_sum($a_qtys);
        // ใช้ round เพื่อป้องกันปัญหาเศษทศนิยมคลาดเคลื่อนของ PHP
        if (round($total_sum, 2) != 100.00) {
            echo json_encode(['status' => 'error', 'message' => 'ผลรวมของปริมาณทั้งหมดต้องเท่ากับ 100 พอดี (ปัจจุบัน: '.$total_sum.')']);
            exit();
        }

        // เช็คชื่อสูตรซ้ำ
        if (empty($formulaID)) {
            $check_sql = "SELECT COUNT(*) AS total FROM formula WHERE name_formula = '$name_formula'";
        } else {
            $check_sql = "SELECT COUNT(*) AS total FROM formula WHERE name_formula = '$name_formula' AND formulaID != '$formulaID'";
        }
        $check_res = mysqli_query($link, $check_sql);
        $check_row = mysqli_fetch_assoc($check_res);
        if ($check_row['total'] > 0) {
            echo json_encode(['status' => 'error', 'message' => 'ชื่อสูตรปุ๋ยผสมนี้มีอยู่ในระบบแล้ว!']);
            exit();
        }

        mysqli_begin_transaction($link);
        try {
            if (empty($formulaID)) { 
                // เพิ่มสูตรใหม่
                $sql_f = "INSERT INTO formula (name_formula, mother_fertilizer_id, additives_fertilizer_id) VALUES ('$name_formula', '0', '0')";
                if(!mysqli_query($link, $sql_f)) throw new Exception(mysqli_error($link));
                $formulaID = mysqli_insert_id($link);
            } else {
                // อัปเดตสูตรเดิม และลบรายการลูกเก่าทิ้งก่อน
                $sql_u = "UPDATE formula SET name_formula='$name_formula' WHERE formulaID='$formulaID'";
                if(!mysqli_query($link, $sql_u)) throw new Exception(mysqli_error($link));
                mysqli_query($link, "DELETE FROM mother_fertilizer WHERE formulaID='$formulaID'");
                mysqli_query($link, "DELETE FROM additives_fertilizer WHERE formulaID='$formulaID'");
            }

            // บันทึกรายการแม่ปุ๋ยทั้งหมด
            for($i=0; $i < count($m_ids); $i++) {
                if(!empty($m_ids[$i]) && !empty($m_qtys[$i])) {
                    $mid = mysqli_real_escape_string($link, $m_ids[$i]);
                    $mqty = mysqli_real_escape_string($link, $m_qtys[$i]);
                    $sql_m = "INSERT INTO mother_fertilizer (formulaID, mother_fertilizer_name_id, mother_quantity) VALUES ('$formulaID', '$mid', '$mqty')";
                    if(!mysqli_query($link, $sql_m)) throw new Exception("ตารางแม่ปุ๋ย: " . mysqli_error($link));
                }
            }

            // บันทึกรายการสารเติมแต่งทั้งหมด (ทำงานก็ต่อเมื่อมีการกรอกมาเท่านั้น)
            for($i=0; $i < count($a_ids); $i++) {
                if(!empty($a_ids[$i]) && !empty($a_qtys[$i])) {
                    $aid = mysqli_real_escape_string($link, $a_ids[$i]);
                    $aqty = mysqli_real_escape_string($link, $a_qtys[$i]);
                    $sql_a = "INSERT INTO additives_fertilizer (formulaID, additives_fertilizer_name_id, additives_quantity) VALUES ('$formulaID', '$aid', '$aqty')";
                    if(!mysqli_query($link, $sql_a)) throw new Exception("ตารางสารเติมแต่ง: " . mysqli_error($link));
                }
            }

            mysqli_commit($link);
            echo json_encode(['status' => 'success', 'message' => 'บันทึกสูตรปุ๋ยผสมสำเร็จ']);

        } catch (Exception $e) {
            mysqli_rollback($link); 
            echo json_encode(['status' => 'error', 'message' => 'เกิดข้อผิดพลาด: ' . $e->getMessage()]);
        }
        exit();
    }
    
    // -----------------------------------------
    // ฟังก์ชัน: ลบสูตรปุ๋ย
    // -----------------------------------------
    if ($action == 'delete_formula') {
        $id = mysqli_real_escape_string($link, $_POST['id']);
        
        // ❗ 1. เพิ่มเงื่อนไขตรวจสอบว่าสูตรปุ๋ยถูกใช้งานใน sahakorn_process หรือไม่ ❗
        // หากชื่อคอลัมน์ในตาราง sahakorn_process ของคุณไม่ใช่ formulaID ให้แก้ตรง WHERE ด้านล่างนี้นะครับ
        $check_sahakorn_sql = "SELECT COUNT(*) AS total FROM sahakorn_process WHERE formulaID = '$id'";
        $check_sahakorn_res = mysqli_query($link, $check_sahakorn_sql);
        
        if ($check_sahakorn_res) {
            $row_sahakorn = mysqli_fetch_assoc($check_sahakorn_res);
            if ($row_sahakorn['total'] > 0) {
                // ถ้ามีข้อมูลอยู่ ให้ส่ง error แจ้งเตือนและหยุดการลบข้อมูลทันที
                echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบได้! เนื่องจากสูตรปุ๋ยนี้ถูกใช้งานในข้อมูลแปรรูปปุ๋ย (sahakorn_process) แล้ว']);
                exit();
            }
        }
        
        // 2. ถ้าไม่มีข้อมูลค้างอยู่ ถึงจะเริ่มทำงานคำสั่งลบข้อมูลตามปกติ
        mysqli_begin_transaction($link);
        try {
            mysqli_query($link, "DELETE FROM formula WHERE formulaID='$id'");
            mysqli_query($link, "DELETE FROM mother_fertilizer WHERE formulaID='$id'");
            mysqli_query($link, "DELETE FROM additives_fertilizer WHERE formulaID='$id'");
            
            mysqli_commit($link);
            echo json_encode(['status' => 'success', 'message' => 'ลบสูตรปุ๋ยสำเร็จ']);
        } catch (Exception $e) {
            mysqli_rollback($link);
            echo json_encode(['status' => 'error', 'message' => 'ลบข้อมูลไม่สำเร็จ: ' . $e->getMessage()]);
        }
        exit();
    }
}
?>

<!doctype html>
<html lang="en">
<?php include 'head.php'; ?>
<style>
    .dynamic-row { background: #f9f9f9; padding: 10px; margin-bottom: 10px; border-radius: 5px; position: relative; }
    .btn-remove-row { margin-top: 25px; width: 100%; }
    .sum-display { font-size: 1.2rem; font-weight: bold; margin-top: 15px; padding: 10px; border-radius: 5px; text-align: right; }
    .sum-ok { background: #dff0d8; color: #3c763d; }
    .sum-error { background: #f2dede; color: #a94442; }
    
    .detail-list { 
        display: flex; 
        justify-content: flex-start; 
        align-items: center; 
        border-bottom: 1px dashed #ddd; 
        padding: 8px 0; 
    }
    .detail-list:last-child { border-bottom: none; }
    .detail-name { 
        font-size: 16px; 
        color: #333; 
        min-width: 140px; 
    } 
    .detail-qty { 
        font-size: 14px; 
        font-weight: bold; 
        padding: 4px 12px; 
        border-radius: 12px; 
        margin-left: 10px; 
    } 
    .qty-rose { background-color: #e91e63; color: white; }
    .qty-info { background-color: #00bcd4; color: white; }
</style>
<body>
    <div class="wrapper">
      <?php include 'leftside.php'; ?>
        <div class="main-panel">  
       <?php include 'header.php'; ?>
            
            <div class="content">
                <div class="container-fluid">      
                 <div class="col-md-12">
                     
                     <nav aria-label="breadcrumb">
                       <ol class="breadcrumb">
                           <li class="breadcrumb-item"><a href="home.php">หน้าหลัก</a></li>
                           <li class="breadcrumb-item active" aria-current="page">จัดการสูตรปุ๋ยผสม</li>
                       </ol>
                     </nav>

                     <button type="button" class="btn btn-primary" id="btnAddFormula">
                         <i class="material-icons"><i class="fas fa-folder-plus"></i></i> เพิ่มสูตรปุ๋ยผสม
                     </button>
                     
                     <?php
                          $sql_formula = "SELECT 
                                            f.formulaID, 
                                            f.name_formula, 
                                            (SELECT GROUP_CONCAT(
                                                CONCAT('<div class=\"detail-list\"><span class=\"detail-name\">', m.mother_name, '</span><span class=\"detail-qty qty-rose\">', mf.mother_quantity, '</span></div>') 
                                                SEPARATOR '') 
                                             FROM mother_fertilizer mf 
                                             JOIN mother_name m ON mf.mother_fertilizer_name_id = m.mother_name_id 
                                             WHERE mf.formulaID = f.formulaID) AS mother_details,
                                            (SELECT GROUP_CONCAT(
                                                CONCAT('<div class=\"detail-list\"><span class=\"detail-name\">', a.additives_name, '</span><span class=\"detail-qty qty-info\">', af.additives_quantity, '</span></div>') 
                                                SEPARATOR '') 
                                             FROM additives_fertilizer af 
                                             JOIN additives a ON af.additives_fertilizer_name_id = a.additives_id 
                                             WHERE af.formulaID = f.formulaID) AS additive_details
                                          FROM formula f
                                          ORDER BY f.formulaID DESC";
                          $result_formula = mysqli_query($link, $sql_formula);     
                     ?>
                     
                     <div class="card">
                         <div class="card-header card-header-icon" data-background-color="rose">
                             <i class="material-icons"><i class="fas fa-calendar-week"></i></i>
                         </div>
                         <h4 class="card-title">จัดการสูตรปุ๋ยผสม</h4>
                         <div class="card-content">
                             <table class="table table-striped table-no-bordered table-hover dt-table" width="100%" style="width: 100%;">
                                 <thead>
                                     <tr>
                                         <th class="text-center" style="width: 5%; font-size: 15px;">ลำดับ</th>
                                         <th style="width: 25%; font-size: 15px;">ชื่อสูตรปุ๋ยผสม</th>
                                         <th style="width: 30%; font-size: 15px;">ข้อมูลแม่ปุ๋ย (ปริมาณ)</th>
                                         <th style="width: 30%; font-size: 15px;">ข้อมูลสารเติมแต่ง (ปริมาณ)</th>
                                         <th class="text-right" style="width: 10%; font-size: 15px;">จัดการ</th>
                                     </tr>
                                 </thead>
                                 <tbody>
                                    <?php 
                                    $i=1;
                                    if($result_formula) {
                                        while ($row = mysqli_fetch_array($result_formula)) { ?>
                                        <tr>
                                            <td class="text-center" style="font-size: 16px;"><?php echo $i; ?></td>
                                            <td><b style="font-size: 16px; color: #333;"><?php echo $row['name_formula']; ?></b></td>
                                            <td><?php echo !empty($row['mother_details']) ? $row['mother_details'] : '<div class="text-muted" style="font-size:16px;">-</div>'; ?></td>
                                            <td><?php echo !empty($row['additive_details']) ? $row['additive_details'] : '<div class="text-muted" style="font-size:16px;">-</div>'; ?></td>
                                            <td class="td-actions text-right">                                      
                                                <button type="button" class="btn btn-success btn-round btn-edit" 
                                                    data-id="<?php echo $row['formulaID']; ?>" title="แก้ไขข้อมูล">
                                                    <i class="material-icons"><i class="far fa-edit"></i></i>
                                                </button>
                                                <button id="<?php echo $row['formulaID']; ?>" title="ลบข้อมูล" class="btn btn-danger btn-round btn-delete">
                                                    <i class="material-icons"><i class="far fa-times-circle"></i></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php $i++; } 
                                    } ?>          
                                 </tbody>
                             </table>
                         </div>
                     </div>
                            
                </div>
              </div>
            </div>
        
          <?php include 'footer1.php'; ?> 
        </div>
    </div>
<?php include 'footer2.php'; ?>

<?php 
// ดึงข้อมูลตัวเลือกเพื่อนำไปใช้ใน JavaScript
$motherOptions = '<option value="">-- เลือกแม่ปุ๋ย --</option>';
$opt_m = mysqli_query($link, "SELECT * FROM mother_name ORDER BY mother_name_id ASC");
while($m = mysqli_fetch_array($opt_m)) {
    $motherOptions .= '<option value="'.$m['mother_name_id'].'">'.$m['mother_name'].'</option>';
}

$additiveOptions = '<option value="">-- เลือกสารเติมแต่ง --</option>';
$opt_a = mysqli_query($link, "SELECT * FROM additives ORDER BY additives_id ASC");
while($a = mysqli_fetch_array($opt_a)) {
    $additiveOptions .= '<option value="'.$a['additives_id'].'">'.$a['additives_name'].'</option>';
}
?>

<div class="modal fade" id="modalFormula" tabindex="-1" role="dialog" style="overflow-y: auto;">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form id="formFormula">
        <div class="modal-header">
          <h4 class="modal-title" id="titleFormula">เพิ่มสูตรปุ๋ยผสม</h4>
        </div>
        <div class="modal-body">
          <input type="hidden" name="action" value="save_formula">
          <input type="hidden" name="formulaID" id="formulaID">
          
          <div class="form-group">
            <label class="control-label">ชื่อสูตรปุ๋ยผสม</label>
            <input type="text" class="form-control" name="name_formula" id="name_formula" required>
          </div>

          <hr>
          <div class="clearfix">
              <h5 class="pull-left" style="font-weight: bold; color: #e91e63;">ส่วนของแม่ปุ๋ย</h5>
              <button type="button" class="btn btn-sm btn-rose pull-right" id="btnAddMotherRow"><i class="fas fa-plus"></i> เพิ่มแม่ปุ๋ย</button>
          </div>
          <div id="motherWrapper"></div>

          <hr>
          <div class="clearfix">
              <h5 class="pull-left" style="font-weight: bold; color: #00bcd4;">ส่วนของสารเติมแต่ง <span style="font-size: 13px; color: #999; font-weight: normal;">(ไม่บังคับ)</span></h5>
              <button type="button" class="btn btn-sm btn-info pull-right" id="btnAddAdditiveRow"><i class="fas fa-plus"></i> เพิ่มสารเติมแต่ง</button>
          </div>
          <div id="additiveWrapper"></div>

          <div id="totalSumBox" class="sum-display sum-error">
              ผลรวมคิดเป็นร้อยละ 100 เท่านั้น: <span id="totalSumText">0.00</span> / 100
          </div>
          
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-success" id="btnSaveFormula" disabled>บันทึกสูตรปุ๋ย</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
    
    $('.dt-table').DataTable({
        "pagingType": "full_numbers",
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        responsive: true,
        language: {
           "search": "ค้นหา:",
           "emptyTable": "ไม่มีข้อมูลในตาราง",
           "info": "แสดง _START_ ถึง _END_ จาก _TOTAL_ แถว",
           "lengthMenu": "แสดง _MENU_ แถว",
           "paginate": { "first": "หน้าแรก", "previous": "ก่อนหน้า", "next": "ถัดไป", "last": "หน้าสุดท้าย" }
        }
    });

    var motherOptions = `<?php echo $motherOptions; ?>`;
    var additiveOptions = `<?php echo $additiveOptions; ?>`;

    function createMotherRow(id = '', qty = '') {
        var html = `
            <div class="row dynamic-row">
                <div class="col-md-6">
                    <label>เลือกแม่ปุ๋ย</label>
                    <select class="form-control select-mother" name="mother_name_id[]" required>
                        ${motherOptions}
                    </select>
                </div>
                <div class="col-md-4">
                    <label>ปริมาณ</label>
                    <input type="number" step="0.01" min="0" class="form-control qty-input" name="mother_qty[]" value="${qty}" required>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-danger btn-sm btn-remove-row"><i class="fas fa-trash"></i></button>
                </div>
            </div>`;
        var $row = $(html);
        if(id !== '') { $row.find('.select-mother').val(id); }
        $('#motherWrapper').append($row);
    }

    function createAdditiveRow(id = '', qty = '') {
        var html = `
            <div class="row dynamic-row">
                <div class="col-md-6">
                    <label>เลือกสารเติมแต่ง</label>
                    <select class="form-control select-additive" name="additive_name_id[]" required>
                        ${additiveOptions}
                    </select>
                </div>
                <div class="col-md-4">
                    <label>ปริมาณ</label>
                    <input type="number" step="0.01" min="0" class="form-control qty-input" name="additive_qty[]" value="${qty}" required>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-danger btn-sm btn-remove-row"><i class="fas fa-trash"></i></button>
                </div>
            </div>`;
        var $row = $(html);
        if(id !== '') { $row.find('.select-additive').val(id); }
        $('#additiveWrapper').append($row);
    }

    function calculateTotal() {
        var total = 0;
        $('.qty-input').each(function(){
            var val = parseFloat($(this).val());
            if(!isNaN(val)) { total += val; }
        });
        
        var totalFixed = total.toFixed(2);
        $('#totalSumText').text(totalFixed);
        
        // ❗ เช็คเงื่อนไข: ผลรวมต้อง 100 พอดีเป๊ะเท่านั้น
        if(totalFixed === '100.00') {
            $('#totalSumBox').removeClass('sum-error').addClass('sum-ok');
            $('#totalSumText').css('color', 'green');
            $('#btnSaveFormula').prop('disabled', false); // ปลดล็อกปุ่มบันทึก
        } else {
            $('#totalSumBox').removeClass('sum-ok').addClass('sum-error');
            $('#totalSumText').css('color', 'red');
            $('#btnSaveFormula').prop('disabled', true); // ล็อกปุ่มบันทึก
        }
    }

    $('#btnAddMotherRow').click(function(){ createMotherRow(); calculateTotal(); });
    $('#btnAddAdditiveRow').click(function(){ createAdditiveRow(); calculateTotal(); });

    $(document).on('click', '.btn-remove-row', function(){
        $(this).closest('.dynamic-row').remove();
        calculateTotal();
    });

    $(document).on('input', '.qty-input', function(){
        calculateTotal();
    });
    
    $('#btnAddFormula').click(function(){
        $('#titleFormula').text('เพิ่มสูตรปุ๋ยผสม');
        $('#formulaID').val(''); 
        $('#name_formula').val(''); 
        $('#motherWrapper').empty();
        $('#additiveWrapper').empty();
        
        createMotherRow(); // สร้างช่องแม่ปุ๋ย 1 ช่องให้เป็นค่าเริ่มต้น
        // ไม่สร้างช่องสารเติมแต่ง เพื่อให้เป็นตัวเลือกจริงๆ
        
        calculateTotal();
        $('#modalFormula').modal('show');
    });

    // ❗ แก้ไข: ใช้ Event Delegation สำหรับปุ่มแก้ไข เพื่อรองรับตารางหน้า 2 เป็นต้นไป
    $(document).on('click', '.btn-edit', function(){
        var uid = $(this).data('id');
        $('#titleFormula').text('กำลังโหลดข้อมูล...');
        $('#motherWrapper').empty();
        $('#additiveWrapper').empty();
        
        $.post(window.location.href, { action: 'get_formula', id: uid }, function(data) {
            if(data.status === 'success') {
                $('#titleFormula').text('แก้ไขสูตรปุ๋ยผสม');
                $('#formulaID').val(data.formula.formulaID);
                $('#name_formula').val(data.formula.name_formula);
                
                // ดึงข้อมูลแม่ปุ๋ย
                if(data.mothers.length > 0) {
                    $.each(data.mothers, function(i, val){ createMotherRow(val.mother_fertilizer_name_id, val.mother_quantity); });
                } else { createMotherRow(); }
                
                // ดึงข้อมูลสารเติมแต่ง (ถ้ามีก็แสดง ถ้าไม่มีก็ปล่อยว่างไว้)
                if(data.additives.length > 0) {
                    $.each(data.additives, function(i, val){ createAdditiveRow(val.additives_fertilizer_name_id, val.additives_quantity); });
                }
                
                calculateTotal();
                $('#modalFormula').modal('show');
            } else {
                swal("ข้อผิดพลาด", "ไม่สามารถโหลดข้อมูลได้", "error");
            }
        }, 'json');
    });

    $('#formFormula').submit(function(e){
        e.preventDefault();
        
        var total = parseFloat($('#totalSumText').text());
        // ตรวจสอบซ้ำอีกรอบก่อน Submit ป้องกันความผิดพลาด
        if(total.toFixed(2) !== '100.00') {
            swal("แจ้งเตือน", "ปริมาณรวมต้องเท่ากับ 100 พอดี ไม่สามารถบันทึกได้", "warning");
            return false;
        }

        $.ajax({
            type: 'POST',
            url: window.location.href, 
            data: $(this).serialize(),
            success: function(response){
                if(response.status === 'success'){
                    $('#modalFormula').modal('hide');
                    swal({title: "สำเร็จ!", text: response.message, type: "success"}, function(){
                        location.reload(); 
                    });
                } else {
                    swal("ข้อผิดพลาด!", response.message, "error");
                }
            },
            error: function(xhr) {
                swal("ข้อผิดพลาดเซิร์ฟเวอร์!", xhr.responseText.substring(0, 150) + "...", "error");
            }
        });
    });

    // ❗ แก้ไข: ใช้ Event Delegation สำหรับปุ่มลบ เพื่อรองรับตารางหน้า 2 เป็นต้นไป
    $(document).on("click", ".btn-delete", function(e) {
         e.preventDefault();
         var uid = $(this).attr('id');
         swal({
             title: "ลบสูตรปุ๋ยนี้?", 
             text: "ข้อมูลแม่ปุ๋ยและสารเติมแต่งของสูตรนี้จะถูกลบไปด้วย!", 
             type: "warning",
             showCancelButton: true, 
             confirmButtonColor: '#d33', 
             confirmButtonText: "ตกลง, ลบ!",
             cancelButtonText: "ยกเลิก",
             closeOnConfirm: false
          }, function(isConfirm) {
             if (isConfirm) {
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    dataType: 'json',
                    data: { action: 'delete_formula', id: uid },
                    success: function(data) {
                        if (data.status === 'error') {
                            // แจ้งเตือน Error กรณีถูกใช้งานอยู่ในตารางอื่น
                            swal("แจ้งเตือน!", data.message, "error");
                        } else {
                            swal({title: "สำเร็จ!", text: data.message, type: "success"}, function(){
                                location.reload(); 
                            });
                        }
                    },
                    error: function(xhr) {
                        swal("ระบบขัดข้อง!", xhr.responseText.substring(0, 150) + "...", "error");
                    }
                });
            }
         });
    });

});
</script>
</body>
</html>

Zerion Mini Shell 1.0