切换复选框时更新数据库

Updating a database when a checkbox is toggled

我有一个脚本,当一个复选框被切换时,它会使用 PHP 和 AJAX 来更新数据库,它部分有效,但我遇到了问题,因为它没有更新到正确的状态我相信这是因为脚本 运行 的速度有多快,但我不太确定如何修复它。下面是我的代码;

HTML/PHP 这是我搜索数据库以列出当前角色及其状态的地方

                    <?php
                    $roleQuery = $pdo->prepare("SELECT * FROM userRoles WHERE userId = ? ORDER BY roleId DESC");
                    $roleQuery->execute([$userId]);
                    while ($role = $roleQuery->fetch()) {

                      $roleTimestampOld = strtotime($role['roleTimestamp']);
                      $roleTimestampNew = date( 'd-m-Y @ H:m:i', $roleTimestampOld);

                      if ($role['roleSet'] == 1) {
                        $roleSet = "checked";
                      } else {
                        $roleSet = "";
                      }
                    ?>
                      <tr>
                        <td><?= ucwords($role['roleType']); ?></td>
                        <td>
                          <div class="switch">
                            <label>
                              Off
                              <input name="roleChecker<?= $role['roleId']; ?>" value="<?= $role['roleId']; ?>" id="roleChecker<?= $role['roleId']; ?>" <?= $roleSet; ?> type="checkbox">
                              <span class="lever"></span>
                              On
                            </label>
                          </div>
                        </td>
                      </tr>
                    <?php
                    }
                    ?>

JavaScript/AJAX

      $('input[type="checkbox"]').click(function(){
              var checkPosition = 0;

             if ($('input[type="checkbox"]').is(":checked")) {
                  var checkPosition = 1;
             }

              var id = $(this).val();
              $.ajax({
                   url:"scripts/ajaxUpdateUserRole.php",
                   method:"POST",
                   data:{checkPosition:checkPosition,id:id,},
                   success: function(data){
                      alert(data);
                  },
             });

         });

PHP 更新数据库

if(isset($_POST["checkPosition"])) {

  $role = $_POST['checkPosition'];
  $id = $_POST['id'];
  $updateRoleQuery = $pdo->prepare("UPDATE userRoles SET roleSet = ? WHERE roleId = ?")->execute([$role, $id]);
  $updateRoleQuery = null;

  echo "Role Updated";
  print_r($_POST);
  }

您当前正在检查是否选中了任何 复选框,而不是您要发送的复选框。

更改您的支票

// This will check if any checkbox on the page is checked
if ($('input[type="checkbox"]').is(":checked")) {
    var checkPosition = 1;
}

// This will only check the checkbox the user changed
if ($(this).is(":checked")) {
    var checkPosition = 1;
}

但是,如果您只是在检查数据库时更新数据库,那么您不妨将 ajax 代码放在 if-statement 中。然后它只会在复选框被选中时被调用。