简体   繁体   中英

Updating a database when a checkbox is toggled

I have a script that will use PHP and AJAX to update a database when a checkbox is toggled and it partly works but I'm having difficulty where it's not updating with the correct status and I believe it's because of how quick the script is running but i'm not too sure how to fix it. Below is my code;

HTML/PHP This is where I search a database to list the current roles and their status

                    <?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 Update the database

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);
  }

You're currently checking if any checkbox is checked, not specifically the one you're sending.

Change your check from

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

to

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

However, if you're only going to update the database in case it's checked, then you might just as well put your ajax code inside that if-statement. Then it will only be called if the checkbox is checked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM