Link to home
Start Free TrialLog in
Avatar of Adebayo Ojo
Adebayo OjoFlag for Nigeria

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

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

Open in new window


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

?>

Open in new window

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

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

?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Adebayo Ojo

ASKER

Thanks for this.