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 >
<label>
Off
<input name="roleChecker<?= $role['roleId']; ?>" value="<?= $role['roleId']; ?>" id="roleChecker<?= $role['roleId']; ?>" <?= $roleSet; ?> type="checkbox">
<span ></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);
}
CodePudding user response:
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.