Adebayo Ojo
asked on
How to store checkbox status in db as 1 or 0 using ajax
I want to store 1 when checkbox is checked and 0 when not checked. But my code is only able to store 1 in my database, even though my function returned both 'true' and 'false' appropriately, my database only shows 1 for both checked and unchecked. Below is my code:
Jquery/Ajax
PHP
Jquery/Ajax
function checkCheckboxState() {
if ($('input[id*="mobile"]').prop('checked') == true) {
// execute AJAX request here
$.ajax({
type: 'POST',
url: 'functions/mobilecheck.php',
data: { 'checked': true },
});
} else {
$.ajax({
type: 'POST',
url: 'functions/mobilecheck.php',
data: { 'checked': false },
});
}
}
PHP
<?php
if(true){
$sql = "UPDATE useroptions SET mobilecheck='1' WHERE username='$log_username'";
$query = mysqli_query($db_connect, $sql);
} else {
$sql = "UPDATE useroptions SET mobilecheck='0' WHERE username='$log_username'";
$query = mysqli_query($db_connect, $sql);
}
?>
if(true) makes your code Always use that option. You're not doing a comparison with that code.
Yes, you have to get the data from $_POST array and then do the comparison:
<?php
$checked = $_POST['checked'];
if( $checked == true ){
$sql = "UPDATE useroptions SET mobilecheck='1' WHERE username='$log_username'";
$query = mysqli_query($db_connect, $sql);
} else {
$sql = "UPDATE useroptions SET mobilecheck='0' WHERE username='$log_username'";
$query = mysqli_query($db_connect, $sql);
}
?>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for this.