更新Mysql记录Onclick Bootrstrap复选框切换

时间:2017-07-08 00:02:54

标签: php jquery mysql ajax

我想编辑所选列的状态字段onclick bootstrap复选框切换.....请帮助 示例: 1 即可。如果status处于活动状态,那么当用户单击时,它应该在数据库中更新为非活动状态并重新加载页面。 的 2 即可。如果状态为非活动状态,那么当用户单击时,它应该在数据库中更新为活动状态并重新加载页面。

enter image description here

获取数据库

<?php 

require_once 'db_config.php';

$output = array('data' => array());


// do not fetch status 3 because it is deleted
$sql = "SELECT *,emailnotificationstable.id as sid FROM notificationslist";
$query = $connect->query($sql);

$num_rows = mysqli_num_rows($query);

$x = $num_rows;
while ($row = $query->fetch_assoc()) {
    // activate button
    $activateButton = '';
    if ($row['status'] == 1) {
            $activateButton = 
            '<input type="checkbox" id="toggleBtn" name="toggleBtn" checked data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
    } elseif ($row['status'] == 2) {
            $activateButton = 
            '<input type="checkbox" id="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
    }

    // extra code here

    $output['data'][] = array(
        $x,
        $activateButton,
        $row['date'],
        $row['notificationname'],
        $row['employeename'],
        $createdby,
        $editedby,
        $editeddate,
        $deleteButton,

    );

    $x--;
}

// database connection close
$connect->close();

echo json_encode($output);

Jquery的

// global the manage memeber table 
var mytable;

$(document).ready(function() {
    mytable = $("#mytable").DataTable({
        "ajax": "../pages/php_action/salesexe/retriveemailnotifications.php",
        "order": [],
"fnDrawCallback": function() {
    jQuery('#mytable #adBtn').bootstrapToggle();
}
        });



});



function editMember(sid = null) {
    if(sid) {

    // remove the error 
    $(".form-group").removeClass('has-error').removeClass('has-success');
    $(".text-danger").remove();
    // empty the message div
    $(".edit-messages").html("");

    // remove the id
    $("#membersid").remove();
    // click on toggle button
    $("#adBtn").click(function() {

        $.ajax({
            url: 'notifstatus.php',
            type: 'post',
            data: {membersid : sid},
            dataType: 'json',
            success:function(response) {

                if(response.success == true) {                      
                    $(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                          '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                        '</div>');
                    // refresh the table
                    mytable.ajax.reload(null, false);

                } else {
                    $(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                          '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                        '</div>');
                }
            }
        });
    }); // click toggle btn
} else {
    alert('Error: Refresh the page again');
}
}

更新

<?php 

require_once 'db_config.php';

$output = array('success' => false, 'messages' => array());

$membersId = $_POST['membersid'];

// update record to inactive
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = $membersId";

$query = $connect->query($sql);

if($query === TRUE) {
    $output['success'] = true;
    $output['messages'] = 'Notification trigger successfullt activated for selected user';
} else {
    $output['success'] = false;
    $output['messages'] = 'Error while activating notification trigger for selected user,';
}
// close database connection
$connect->close();

echo json_encode($output);

1 个答案:

答案 0 :(得分:1)

您正在考虑通过重新加载页面来复杂化,而不是使用API​​。您只想获取状态并更新所需的部分,这意味着您需要一种正确的方法来识别表中的行。另外,html id在页面中必须是唯一的,最好删除它。

您有几个选择:

  1. 使用 datatables ajax requests ,以便它可以处理不同cols的多个编辑。
  2. 使用jquery和bootstrap打开和关闭按钮。
  3. 下面显示的是后者:

    $(function() {
      // hooking event only on buttons, can do tr's as well.
      $('.toggleBtn').click(function(){
        $.ajax({
          url: 'notifstatus.php',
          type: 'post',
          data: {
            id : $(this).val(),
            status: $(this).prop('checked')
          },
          dataType: 'json',
          success: function(response){
            if(response.success){
              $(this).bootstrapToggle('enable');
              console.log(response.message);
            } else {
              $(this).bootstrapToggle('disable');
              BootstrapDialog.show({
                title: 'failed to update status',
                message: response.status + response.messages
              });
            }
          },
          error: function(xhr, textStatus, errorThrown) {
            BootstrapDialog.show({
              title: textStatus,
              message: errorThrown
            });
          }
        });
      });
    });
    

    现在对构建的唯一响应如下:

    <?php 
    
      require_once 'db_config.php';
    
      if(isset($_POST['status']) && $_POST['status']){
        // user requests to turn off
        $sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = ?"; // SQL injection, use prepared statements. fix it.
      } else {
        // user requests to turn on, other query.
      }
    
      $success;
      $status = 0;
      $message = 'Error while activating notification trigger for selected user,';
    
      if($query = $connect->query($sql)){
        if($row = $query->fetch_assoc()){
          $success = true;
          $message = 'Notification trigger successfully activated for selected user';
          $status = $row['status'];
        }
      }
    
      die(json_encode([
        'success'  => $success,
        'messages' => $message,
        'status'   => $status
      ]));
    ?>
    

    应该这样做,不需要请求所有数据来更新单个值。