Ajax 在使用 php&mysql 选中复选框时进行穿行

问题描述 投票:0回答:1

尝试学习一些 php 和 mysql,所以我正在处理一个待办事项列表,我希望当每个任务所具有的复选框被选中时,待办任务能够获得一条直线,如果未选中,则再次删除。

就像我这里一样:

我已经这样做了,这样我就可以从数据库中的变量进行线路传输,如下所示:

<input class="form-check-input form-check-input-todolist flex-shrink-0 my-1 me-2 form-check-input-undefined" type="checkbox" data-event-propagation-prevent="data-event-propagation-prevent" id="checkbox-todo-<?= $todoTask_Data['task_id'] ?>" <?php if($todoTask_Data['task_checked'] == 'true') {echo 'checked';} ; ?> />

现在我需要了解当单击复选框时如何将“true”变量添加到 mysqli 中的 task_checked 列。

之前没有真正使用过ajax/js,所以弄清楚如何做到这一点非常令人困惑。但我想我现在有了这个想法,但仍然无法让它发挥作用。

这是我得到的剧本

  $(document).ready(function() {
$('.checkbox-todo').on('change', function() {
  if (this.checked) {
    var checkboxID = $(this).attr('id');


    $.ajax({
      url: "update_TodoTask.php",
      method: "POST",
      data: { checkboxID: checkboxID },
      success: function(response) {

      }
    });
  }
});
});

在 update_TodoTask.php 中我得到了这样的东西:

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['checkboxID'])) {
 $checkboxID = $_POST['checkboxID'];


header('Location: test.php');
}

这是html代码:https://pastecode.io/s/zw4thpoe

但我什至不认为按下时它是与 update_TodoTask.php 通信。当我按下复选框时,它不应该触发标题位置吗?

我不确定我是否告诉 ajax 脚本待办事项列表中的哪个复选框被正确按下?

谁能告诉我我在这里做错了什么?

更新:

当我使用以下命令单击复选标记时,我现在可以将 true 添加到数据库中的 task_checked collomn 中:

$(document).ready(function() {
  $('.form-check-input-todolist').on('change', function() {

    var checkboxID = $(this).attr('id');
    let [c, t, id] = checkboxID.split('-');

    $.ajax({
      url: "update_TodoTask.php",
      method: "POST",
      data: {
        checkboxID: checkboxID,
        id: id, // the Integer portion of ID - useful for sql update statement
        state: ( this.checked ? 1 : 0 ) // Boolean - is it checked? - useful for sql update statement
      },
      success: (res) => {
        console.log(res);
      },
      error: (err) => {
        console.log(`${err.statusText} - problem making AJAX request with ID: ${id}`)
      }
    });

  });
});

我的 update_TodoTask.php 看起来像这样:

    #assumed mySQLi connection
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
      $_POST['checkboxID'],
      $_POST['id'],
      $_POST['state'],
  )){
    $checkboxID = $_POST['checkboxID'];
    $id = $_POST['id'];
    $state = $_POST['state'];
    
    $todo_task_checkmark_update = mysqli_query($conn, "UPDATE todo_tasks SET task_checked = 'true' WHERE task_id = $id");

  };

现在,当我单击其中一个复选标记时,它会在 task_checked 列中使用“true”值更新我的数据库..

我现在需要的最后一件事是当我取消选中待办事项时从数据库中删除复选标记。

我尝试过执行类似下面的代码的操作,但无法让 isset 工作:

    #assumed mySQLi connection
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
      $_POST['checkboxID'],
      $_POST['id'],
      $_POST['state'],
  )){
    $checkboxID = $_POST['checkboxID'];
    $id = $_POST['id'];
    $state = $_POST['state'];

    $query = "SELECT task_checked FROM todo_tasks WHERE task_id = $id";
    $result = $conn->query($query);

    $row = $result->fetch_assoc();
    $todoTask_checkmark_status = $row['task_checked'];


    if (isset($todoTask_checkmark_status)) {
      if ($todoTask_checkmark_status == false) {
          $todo_task_checkmark_update = mysqli_query($conn, "UPDATE todo_tasks SET task_checked = 'true' WHERE task_id = $id");
      } elseif ($todoTask_checkmark_status == true) {
          $todo_task_checkmark_update = mysqli_query($conn, "UPDATE todo_tasks SET task_checked = 'false' WHERE task_id = $id");
      } 
  };

  };

我也尝试了 $_POST['state'] 的 isset 但同样的问题..它甚至不运行 isset 部分..

我做错了什么?

php ajax checkbox
1个回答
0
投票

为了确保更新数据库以反映用户选择的已选中/未选中/已选中性质,您应该为每个输入元素上注册的每个

change
事件发送 AJAX 请求。 AJAX 请求还应该发送已检查的值,以便您可以确定表是否仍应显示已检查或未检查。

您可以分解 STRING id 属性来确定实际的整数值以及

this.checked
布尔值 - 将它们添加到通过 AJAX 发送的 POST 有效负载中。

PHP 代码随后具有实际(大概)ID 值和要在 SQL 更新语句中使用的布尔值。

不用担心 Javascript

state
在发布时是布尔值或字符串,而是可以使用简单的三元运算符轻松将其替换为整数 1 或 0。

$(document).ready(function() {
  $('.form-check-input-todolist').on('change', function() {
    /* 
      Not sure why you need to send ALL the ID of the checkbox, 
      only the integer is relevant most likely?
      
      so - split the ID into parts and select integer
    */
    var checkboxID = $(this).attr('id');
    let [c, t, id] = checkboxID.split('-');
    /* 
      To reflect checked/unchecked in db the ajax request should be sent 
      whenever the user modifies the input checked status.
    */
    $.ajax({
      url: "update_TodoTask.php",
      method: "POST",
      data: {
        checkboxID: checkboxID,
        id: id, // the Integer portion of ID - useful for sql update statement
        state: ( this.checked ? 1 : 0 ) // Boolean - is it checked? - useful for sql update statement
      },
      success: (res) => {
        console.log(res);
        this.parentNode.classList.toggle('linethrough')
      },
      error: (err) => {
        console.log(`${err.statusText} - problem making AJAX request with ID: ${id}`)
        /* 
        the following should not be here for final version 
        it is here only because the AJAX request WILL fail
        here in the snippet
        */
        this.parentNode.classList.toggle('linethrough')
      }
    });

  });
});
.linethrough {
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<label>Task 1
    <input class="form-check-input form-check-input-todolist flex-shrink-0 my-1 me-2 form-check-input-undefined" type="checkbox" data-event-propagation-prevent="data-event-propagation-prevent" id="checkbox-todo-1" />
</label>

<label>Task 2
    <input class="form-check-input form-check-input-todolist flex-shrink-0 my-1 me-2 form-check-input-undefined" type="checkbox" data-event-propagation-prevent="data-event-propagation-prevent" id="checkbox-todo-2" />
</label>

<label>Task 3
    <input class="form-check-input form-check-input-todolist flex-shrink-0 my-1 me-2 form-check-input-undefined" type="checkbox" data-event-propagation-prevent="data-event-propagation-prevent" id="checkbox-todo-3" />
</label>

<label>Task 4
    <input class="form-check-input form-check-input-todolist flex-shrink-0 my-1 me-2 form-check-input-undefined" type="checkbox" data-event-propagation-prevent="data-event-propagation-prevent" id="checkbox-todo-4" />
</label>

你的 PHP 可能有点像这样:

<?php
    #assumed mySQLi connection
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
        $_POST['checkboxID'],
        $_POST['id'],
        $_POST['state'],
    )){
    
        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
        $state=filter_input( INPUT_POST, 'state', FILTER_SANITIZE_NUMBER_INT );
        
        $sql='update `TABLENAME` set `<COLNAME>`=? where `<ID>`=?';
        $stmt=$db->prepare( $sql );
        $stmt->bind_params('ii',$state,$id);
        $stmt->execute();
        
        exit('ok...or other useful stuff');
    }

?>

您不想在脚本末尾使用

header
调用,因为您发送的是 AJAX 请求而不是常规 HTTP GET 请求,因此它不会被接受。相反,将有意义的数据发送回 AJAX 回调函数 - 回调可用于以某种方式更新 DOM 或让用户知道他们做了好事/坏事等

© www.soinside.com 2019 - 2024. All rights reserved.