在PHP中单击复选框时更新状态

时间:2017-03-10 05:29:18

标签: javascript php jquery mysql

我有一个从数据表创建的表,如何在单击复选框时更改状态字段,默认状态为'之前'然后当复选框单击它时更新为'之后'(在数据库字段状态中),然后表重新加载。

此数据显示表

    .....
   foreach ($data as $key) {
    // add new button, checkbox
    $data[$i]['ceklolos'] = '<input type="checkbox"      id_data="'.$data[$i]   ['status_lolos'].'" class="btn btn-primary btnedit" >';
       $i++;
    ...

当其余代码时,每个数据中的复选框单击该数据行从“之前状态”(默认数据库)更新为“状态之后”,之后表重新加载..

谢谢,我正在使用datatable和php

1 个答案:

答案 0 :(得分:1)

首先,将自定义数据属性添加到您的复选框

<input type="checkbox" data-id="'.$data['id'].'" data-status="'.$data['status'].'" ../>

在你的javascript中,

// IIFE (Immediately Invoke Function Expressions)
(function (myapp){
   myapp(window.jQuery, window, document);
}(function myapp($, window, document){
   // $ is now locally scoped
   $(function (){
      // dom is now ready
      var dtTable = $("#sometable").DataTable();

      // dom events
      $(document).on("change", '.btnedit', function (){
          var $this = $(this);
          var id = $this.attr("data-id");
          var status = $this.attr("data-status");

          // send ajax request 
          $.ajax({
             url: 'path-to-your-php-file',
             type: 'post',
             dataType: 'json',
             data: {
                id: id, 
                status: status
             },
             beforeSend: function (){
               // do something here before sending ajax
             },
             success: function (data){
               // do something here
               if( data.success ){
                  // update your table, or any html dom you want here
                  // if you want to add/remove rows from your dataTable,
                  // you can refer here 
                  // https://datatables.net/reference/api/row.add()
                  // https://datatables.net/reference/api/row().remove()
                  // 
               }
             },
             error: function (data){
               // do something here if error 
               // console.warn(data);
             }
          });
      });
   });
   // The rest of the code goes here
}));

在PHP文件中,

<?php 

$id = $_POST['id'];
$status = $_POST['status'];
// do your update codes here
// 
// after successful update return something so in your ajax you
// will know what happened behind the scene
$response = array('success' => false, 'msg' => 'Some error message');
if( some_update_function_success() ){
   $response = array('success' => true, 'msg' => 'Some success message');
}
echo json_encode($response);